2

我试图从 url 栏中获取路线和查询。下面的代码来自 CodeWithMosh 的教程。我在 combineLatest 方法中遇到编译错误。

错误如下:

(属性) paramMap: Observable 类型的参数'{ paramMap: Observable; queryParamMap:可观察的;}' 不可分配给“ObservableInput”类型的参数。
对象字面量只能指定已知属性,而“ObservableInput”类型中不存在“paramMap”

我是角度的新手,我不确定错误是什么意思,我已经尝试遵循这个堆栈溢出答案,但我仍然得到错误。谢谢你。

完整代码如下:

    import { ActivatedRoute } from '@angular/router';
    import { GithubFollowersService } from './../services/github-followers.service';
    import { Component, OnInit } from '@angular/core';
    import 'rxjs/add/Observable/combineLatest';
    import { Observable } from 'rxjs/internal/Observable';
    import { combineLatest } from 'rxjs';

    @Component({
      selector: 'github-followers',
      templateUrl: './github-followers.component.html',
      styleUrls: ['./github-followers.component.css']
    })
    export class GithubFollowersComponent implements OnInit {
      followers : any[];

      constructor(
        private route: ActivatedRoute,
        private service : GithubFollowersService) { }

      ngOnInit() {
        const paramMap = this.route.paramMap;
        const queryParamMap = this.route.queryParamMap;

        combineLatest({
          paramMap, // error here
          queryParamMap
        })
        .subscribe(combined => {
          let id = combined[0].get('id');//the 0 means the 1st 1 which is paramMap from above
          let page = combined[1].get('page');

          this.service.getAll().subscribe(followers => this.followers = followers);
        });


      }

    }
4

3 回答 3

2

如果你使用的是当前版本的 Angular/RxJS,你的导入应该是这样的:

import { combineLatest, Observable } from 'rxjs';

您看到的错误是 combineLatest 的语法不正确。它应该如下所示:

  combineLatest([
    paramMap,
    queryParamMap
  ])

注意[]而不是{}

此外,约定为包含 Observable 的变量加上$.

来自 github 评论:

静态版本combineLatest接受 Observable 数组或每个 Observable 可以直接作为参数。

链接在这里:https ://github.com/ReactiveX/rxjs/blob/95bd8073e33c39a8f8d4ade8bf15c39a1154a879/src/internal/observable/combineLatest.ts

于 2019-09-27T15:13:41.970 回答
1

您正在寻找forkJoin在多个订阅完成时执行特定代码。这样做的伪逻辑是

forkJoin(
  paramMap.pipe(
    tap(res => {
      allParams["param1"] = res.get("param1");
    })
  ),
  queryParamMap.pipe(
    tap(res => {
      allParams["param1"] = res.get("param2");
    })
  )
).subscribe(res => {
  //call your service
});
于 2019-09-27T11:03:39.377 回答
1

只需放弃{ }

        combineLatest(
          paramMap,
          queryParamMap
        )
        .subscribe(combined => {

{ },不[ ],只是列出要合并的流。

https://www.learnrxjs.io/operators/combination/combinelatest.html

于 2019-09-27T15:18:48.823 回答