当所有XHR请求都完成时做一些事情-Angular 7

时间:2019-04-30 22:27:30

标签: angular

在Angular 7中完成所有XHR请求后,我该怎么办?

 getGeneralPage(data, ServiceName: string, Type: string): Observable<Object> {
        const headers = new HttpHeaders();
        const lang = localStorage.getItem('language') === 'en' ? 1 : 2;
        headers.append('Content-Type',
            'application/x-www-form-urlencoded;charset=utf-8');
        return this.http.get(
            this.apiURL + 'MOICDTacsoft/services/'
            + ServiceName + '/' + Type + '?WebsiteID=1&LanguageID='
            + lang + '&uniqueName=' + data, {
                headers: headers
            }).pipe(map(res => res)).finally(() => {
            this.loadingNotifier.next(false);
        });
    }


    getPollPage(categoryID: string, ServiceName: string, Type: string): Observable<Object> {
        const headers = new HttpHeaders();
        const lang = localStorage.getItem('language') === 'en' ? 1 : 2;
        headers.append('Content-Type',
            'application/x-www-form-urlencoded;charset=utf-8');
        return this.http.get(
            this.apiURL + 'MOICDTacsoft/services/'
            + ServiceName + '/' + Type + '?WebsiteID=1&LanguageID='
            + lang + '&CategoryID=' + categoryID, {
                headers: headers
            }).pipe(map(res => res));
    }

上面,我有两个请求,并且我在第一个请求中使用了final,但是在第二个请求完成之前加载变为false并且加载器消失了,所以我如何确保在所有请求时都可以发送新值完成吗?

1 个答案:

答案 0 :(得分:0)

DEMO是如何发出单个请求和一批请求的方法。希望能帮助到你。取决于您对观察站的订阅方式。

这是另一个DEMO,其中可观察者同时扮演着可观察者和观察者的角色。

如果您要使用forkJoin,这是指向SO-POST的链接,以捕获错误。

export class AppComponent {
  todo;
  todos;
  index = 1;

  constructor(private provider: ProviderService) {}

  getTodo() {
    this.provider.getTodo(this.index).subscribe(todo => this.todo = todo);
    this.index++;
  }

  getManyTodos() {
    const todos = [2, 4, 6, 8, 10];
    const todo$ = [];

    todos.forEach(todo => {
      const t$ = this.provider.getTodo(todo);
      todo$.push(t$);
    });

    forkJoin(todo$).subscribe(todos => {
      console.log(todos);
      this.todos = todos;
    });
  }
}



export class ProviderService {

  constructor(private http: HttpClient) {}

  getTodo(todo: number) {
    const url = `https://jsonplaceholder.typicode.com/todos/${todo}`;
    return this.http.get(url);
  }
}