如何处理多个嵌套订阅

时间:2019-07-04 20:00:54

标签: angular typescript angular7

我想 从路由获取id参数 然后用这个来获取任务 然后,如果有任务

,则获取任务父对象的父对象
    Angular CLI: 7.1.4
    Node: 11.6.0
    OS: linux x64
    Angular: 7.1.4
    @angular-devkit/architect         0.11.4
    @angular-devkit/build-angular     0.11.4
    @angular-devkit/build-optimizer   0.11.4
    @angular-devkit/build-webpack     0.11.4
    @angular-devkit/core              7.1.4
    @angular-devkit/schematics        7.1.4
    @ngtools/webpack                  7.1.4
    @schematics/angular               7.1.4
    @schematics/update                0.11.4
    rxjs                              6.3.3
    typescript                        3.1.6
    webpack                           4.23.1

任务服务:

    import { ITask } from '@task/interfaces/task';
    ...
    export class TaskService {
      constructor(private _http: HttpClient) {}
    ...
      get_task(id: number) {
        return this._http.get<ITask>(\`http://127.0.0.1:8000/api/task/${id}\`);
      }

在我的组件中:
收到一项任务有2个订阅


    this._route.params.subscribe((params: Params) => {
      this._task_service
        .get_task(params['id'])
        .subscribe(
          (data: ITask) => { this.task = data; },
          err => { this._log.log('error while fetching task ', err); }
        );
    });

我想

this._route.params   
get_task(params['id'])
if `task.parent` get parent task 

我读了很多小时,在尝试的所有方式上都出现了错误
flatMap().subscribe(...) //类型'Subscription'不能分配给类型'ObservableInput <{}>'

我在互联网上阅读了很多帖子,但我听不懂
有人可以举例说明我如何实现吗?

更新

console.log( 
  'type ',
   typeof this._task_service.get_task(2),
   this._task_service.get_task(2)
);

我明白了

type  object 
{…}
​_isScalar: false
​operator: {…}
  project: function request()
​​  thisArg: undefined
​​  __proto__: Object { call: call(), … }
​source: {…}
  ​​_isScalar: false
  ​​operator: {…}
    ​​​predicate: function
./node_modules/@angular/common/fesm5/http.js/HttpClient.prototype.request/res$<()
    ​​​thisArg: undefined
    ​​​__proto__: Object { call: call(), … }
​​    source: Object { _isScalar: false, source: {…}, operator: {…} }
    ​​__proto__: Object { lift: lift(), subscribe: subscribe(), _trySubscribe: 
  d_trySubscribe(), … }
__proto__: Object { lift: lift(), subscribe: subscribe(), _trySubscribe: _trySubscribe(), … }

1 个答案:

答案 0 :(得分:0)

这应该有效,让我知道,我无法测试您的代码

const subscription = this._route.params.pipe(
  switchMap((params: Params) => combineLatest([
    this._task_service.parentFetchRequest(), // change with your parent fetch request 
    this._task_service.get_task(params['id'])
    ])
  )
  .subscribe(
    ([dataOfParent : ParentType, data: ITask]) => { 
      this.task = data; 
      this.parentTask = dataOfParent
      },
    err => { this._log.log('error while fetching task ', err); }
  );