下面是我的代码,当用户选择选项卡时,我想取消现有呼叫并加载用户单击的选项卡详细信息。
我了解我必须使用switchmap(如果不正确或有更好的选择,请指导我)
我遵循此示例,但由于id具有Valuechanges属性switchmap example
,因此该示例不适用于我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)
);
}
答案 0 :(得分:0)
app.component.html
click事件将发出我在每次按钮单击中选择的按钮。
<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
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);
}
}