使用mergeMap在Angular中合并两个顺序订阅时出现错误

时间:2018-10-17 07:57:28

标签: angular observable rxjs5

我有两个顺序的订阅:

 this.authService.tokenObs.pipe( map(res => res),mergeMap( token =>
    this.service.getUsers(token).subscribe(res2=>{
            console.log('res2', res2)
  })
));

合并地图中的令牌参数出错:

  

类型'(token:{})=>订阅'的参数不可分配给

     

类型'(值:{},索引:数字)=> ObservableInput <{}>'的参数。

     

类型'Subscription'不能分配给类型'ObservableInput <{}>'。

     

类型'Subscription'不能分配给类型'ArrayLike <{}>'。

     

“预订”类型中缺少属性“长度”。 (参数)令牌:{}

我是第一次使用mergeMap,所以不熟悉此错误。

2 个答案:

答案 0 :(得分:1)

您需要像下面那样修改代码

this.authService.tokenObs.pipe(
     map(res => res),
     mergeMap(this.service.getUsers(token))
).subscribe(res2=>{
    console.log('res2', res2)
});

由于您是新手,可以看看工作示例https://stackblitz.com/edit/angular-gsefpz

import { Component } from '@angular/core';
import { map, mergeMap } from 'rxjs/operators';
import { HttpClient} from '@angular/common/http';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';

  constructor(public http: HttpClient) {
    this.http.get('https://jsonplaceholder.typicode.com/users').pipe(
      map(res => res[0].id),
      mergeMap(id => this.http.get(`https://jsonplaceholder.typicode.com/posts?userId=${id}`))
    ).subscribe(res2 => {
      console.log('res2', res2)
    });
  }
}

编辑2:

https://stackblitz.com/edit/angular-gsefpz

更新了用于处理错误的代码。测试将其更改为错误URL的错误情况。

import { Component } from '@angular/core';
import { map, mergeMap, tap, catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';

  constructor(public http: HttpClient) {
    this.http.get('https://jsonplaceholder.typicode.com/users').pipe(
      tap(data => console.log('data >>> ', data)),
      map(res => res[0].id),
      tap(data => console.log('transformed data >>> ', data)),
      mergeMap(id => this.http.get(`https://jsonplaceholder.typicode.com/posts?userId=${id}`)),
      catchError(error => {
        console.log('ERROR >>>> ', JSON.stringify(error));
        return throwError({ status: error.status, errorMsg: error.statusText });
      })
    ).subscribe(res2 => { console.log('res2', res2) }, err => console.log(err));
  }
}

编辑3 对于rxjs 5.5 https://stackblitz.com/edit/angular-5-tutorial-yzowvt

import { Component } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs';

  constructor(public http: HttpClient) {
    this.http.get('https://jsonplaceholder.typicode.com/users')
    .do(data => console.log('data >>> ', data))
    .map(res => res[0].id)
    .do(data => console.log('transformed data >>> ', data))
    .mergeMap(id => this.http.get(`https://jsonplaceholder.typicode.com/posts?userId=${id}`))
    .catch(error => {
        console.log('ERROR >>>> ', JSON.stringify(error));
        return Observable.throw({ status: error.status, errorMsg: error.statusText });
    })
    .subscribe(res2 => { console.log('res2', res2) }, err => console.log(err));
  }

答案 1 :(得分:1)

如果要使用Observable的序列彼此依赖,最好使用“ switchMap”:

onCreate

您还可以使用“ mergeMap”:

import { switchMap } from 'rxjs/operators';

this.authService.tokenObs.pipe(
   switchMap((token) => {
      return this.service.getUsers(token);
   }),
   map((user) => {
      // do what you want;
   })
)

区别在于,如果this.authService.tokenObs更改,则“ switchMap”将取消对服务器的暂挂请求(this.service.getUsers(token))。但是“ mergeMap”不会取消,而是继续执行。 附注:尝试研究并开始使用@ ngrx-store来更好地构建具有Observables的系统架构:https://github.com/ngrx/platform