Использование SwitchMap onTabSelect - PullRequest
1 голос
/ 06 апреля 2019

Ниже приведен мой код, когда пользователь выбирает вкладку, я хочу отменить существующий вызов и загрузить сведения о вкладке, на которые пользователь нажимает.

Я понимаю, что мне нужно использовать switchmap (наведите меня, если это не правильно или лучшая альтернатива)

Я следую этому примеру, и он не работает для меня, так как у идентификатора есть свойство Valuechanges Пример switchmap

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)
 );
}

1 Ответ

0 голосов
/ 06 апреля 2019

app.component.html

событие щелчка будет генерировать кнопку, выбранную мной при каждом нажатии кнопки.

<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 установлено значение 500 мс, которое будет ждать 500 мс, прежде чем будет выбрана выбранная опция

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);
  }
}
...