首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SwitchMap使用onTabSelect

SwitchMap使用onTabSelect
EN

Stack Overflow用户
提问于 2019-04-06 08:38:27
回答 1查看 306关注 0票数 1

下面是我的代码,当用户选择选项卡时,我想取消现有的调用并加载用户单击的选项卡详细信息。

我知道我必须使用switchmap(如果它不正确或更好的替代方案,请指导我)

我遵循了这个示例,但它对我不起作用,因为id具有Valuechanges属性switchmap example

代码语言:javascript
复制
onTabSelect(event: MatTabChangeEvent) {
this.categoryId = this.sections[event.index].categoryId;
this.designService.getDesignsByCategoryId(this.categoryId)
.subscribe(
   (design: any[]) => {
     this.designs = design;
     this.designsCount = design.length + ' Designs';
     this.designsLoaded = true;
  },
   error => (this.errorMessage = error)
 );
}
EN

回答 1

Stack Overflow用户

发布于 2019-04-06 12:07:23

app.component.html

单击事件将发出我在每次单击按钮时选择的按钮。

代码语言:javascript
复制
<div class="tab">
  <button style="height: 50px; width: 100px;" class="tablinks" (click)="tabclickSubject.next(1)">topfunky</button>
  <button style="height: 50px; width: 100px;" class="tablinks" (click)="tabclickSubject.next(2)">roland</button>
  <button style="height: 50px; width: 100px;" class="tablinks" (click)="tabclickSubject.next(3)">lukas</button>
</div>

<div class="tabcontent">
  <h3>{{user.name}}</h3>
  <p>{{user.location}}</p>
</div>

app.component.ts

声明了一个要订阅按钮点击的主题。debounceTime设置为500ms,在发出所选选项之前将等待500ms

代码语言:javascript
复制
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject, Observable, Subscription } from 'rxjs';
import { switchMap, debounceTime } from 'rxjs/operators';
import { User } from './models/user';
import { HttpClient } from '@angular/common/http';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit, OnDestroy {
  user: User;
  tabclickSubject = new Subject();
  subscription: Subscription;

  constructor(private http: HttpClient) { }

  ngOnInit() {
    this.getUser('topfunky').subscribe(
      user => {
        this.user = user;
      }
    );

    this.subscribeToButtonClick();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  subscribeToButtonClick() {
    this.subscription = this.tabclickSubject.pipe(
      debounceTime(500),
      switchMap(option => {
        if (option === 1) {
          return this.getUser('topfunky');
        } else if (option === 2) {
          return this.getUser('roland');
        } else {
          return this.getUser('lukas');
        }
      })
    ).subscribe(reponse => {
      this.user = reponse;
    });
  }

  getUser(name: string): Observable<User> {
    return this.http.get<User>('https://api.github.com/users/' + name);
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55544850

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档