[英]Angular how to use combineLatest to combine routes and queries from website url bar
我試圖從 url 欄獲取路線和查詢。 下面的代碼來自 CodeWithMosh 的教程。 我在 combineLatest 方法中遇到編譯錯誤。
錯誤如下:
(屬性) paramMap: Observable 類型的參數'{ paramMap: Observable; queryParamMap:可觀察的; }' 不可分配給“ObservableInput”類型的參數。
Object 字面量只能指定已知屬性,並且“ObservableInput”類型中不存在“paramMap”
我是 angular 的新手,我不確定錯誤是什么意思,我已經嘗試遵循這個堆棧溢出答案,但我仍然得到錯誤。 謝謝你。
完整代碼如下:
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);
});
}
}
您正在尋找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
});
如果你使用的是當前版本的 Angular/RxJS,你的導入應該是這樣的:
import { combineLatest, Observable } from 'rxjs';
您看到的錯誤是 combineLatest 的語法不正確。 它應該如下所示:
combineLatest([
paramMap,
queryParamMap
])
注意[]
而不是{}
此外,約定使用$
包含 Observable 的變量添加后綴。
來自 github 評論:
combineLatest 的
combineLatest
版本接受 Observable 數組,或者每個 Observable 都可以直接作為參數。
只需放棄{ }
:
combineLatest(
paramMap,
queryParamMap
)
.subscribe(combined => {
沒有{ }
,沒有[ ]
,只列出要組合的流。
https://www.learnrxjs.io/operators/combination/combinelatest.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.