0

我正在使用 Rxjs,我想从以下模式(按顺序)创建一个 Observable:

  1. 从 paramMap$ 获取参数,然后...

  2. 根据 params 的值,将两者 (getData():Observable, getCategories():Observables) 放在一起,然后......

  3. from ([data, categories]) 创建最终对象。

代码如下所示:

//route = this.ActivatedRoute

let obs$ = route.paramMap.pipe(

// combineLatest() is not a pipable operator, so it shouldn't be used inside .pipe()
// also it doesn't accept a function,
// but this just to show you what I want to do.

combineLatest(params=>getData(params.id), params=>getCategories(params.id)),

map(([data, categories])=>{
//do some changes...
return {data,categories}
}
)
)

将此代码放在 Angular 项目中的最佳位置是哪里:

  • constructor()不是最佳实践,因为这是一个长时间运行的操作(实际上它必须执行 API 请求)

  • ngOnInit()不推荐,因为在某些时候我必须更改this.params模板中使用的

...
combineLatest(params=>
   getData(params.id).pipe(
        map(data=>{
            this.params.type=data.type; 
            return data
           })), 
   params=>getCategories(...) 
)

在模板中:

<div>{{params.type}}</div>
4

1 回答 1

3

要在获取参数后对 Observable 进行管道传输,您可以在其中使用switchMap并返回 a forkJoin()

this.route.paramMap.pipe(switchMap((params) => {
    return forkJoin(getData(params.id), getCategories(params.id));
}));

我相信,订阅一个 Observable,做 API 请求,最好都应该去ngOnInit()除非你有一些非常具体的要求,在组件加载时你不希望这些订阅。

this.params目前而言,您可以this.params在使用管道tap()或订阅此 Observable 的地方进行分配。

于 2020-05-06T15:12:20.533 回答