我面临来自RX.js的新HttpClientModule
和map()
功能的问题。
我想要做的是更改来自get()
方法的observable内返回数组的对象。
我的密码:
get(url: string): Observable < any > {
return this.http.get(this.config.baseUrl + url);
}
playerSearch(text: string): Observable < any[] > {
if (text == "" || !text) {
return Observable.of([]);
} else {
return this.auth.get(`/players?$expand=Contact($expand=Blob)&$filter=contains(Contact/LastName, '${text}') or contains(Contact/FirstName, '${text}')`).map((x) => {
return {
Id: x.Id,
Name: x.Contact.FirstName + " " + x.Contact.FatherName.substring(0, 2) + ". " + x.Contact.LastName,
BlobSrc: this.utilitiesService.imageLinkCreator(x)
}
});
}
}
search = (text$: Observable < string > ) =>
text$
.debounceTime(300)
.distinctUntilChanged()
.do(() => this.searching = true)
.switchMap(term =>
this.dataService.playerSearch(term)
.do(() => this.searchFailed = false)
.catch(() => {
this.searchFailed = true;
return Observable.of([]);
}))
.do(() => this.searching = false);
&#13;
我得到的错误:
键入&#39; Observable&lt; {Id:any;名称:字符串; BlobSrc:string; }&GT;&#39;不能分配给&#39; Observable&#39;。
输入&#39; {Id:any;名称:字符串; BlobSrc:string; }&#39;不能指定为&#39;任何[]&#39;。
据我所知,map()
方法返回observable
,其值只有一个对象而不是数组。
返回包含{ Id: any; Name: string; BlobSrc: string; }
个对象数组的observable的正确语法是什么?
答案 0 :(得分:0)
如果您的http请求返回了一系列播放器,那么这就是您的代码的样子:
get(url: string): Observable<any[]> {
return this.http.get(this.config.baseUrl + url);
}
playerSearch(text: string): Observable<any[]> {
if (text == "" || !text) {
return Observable.of([]);
} else {
return this.auth.get(`/players?$expand=Contact($expand=Blob)&$filter=contains(Contact/LastName, '${text}') or contains(Contact/FirstName, '${text}')`).map((arr: any[]) => {
return arr.map(x => ({
Id: x.Id,
Name: x.Contact.FirstName + " " + x.Contact.FatherName.substring(0, 2) + ". " + x.Contact.LastName,
BlobSrc: this.utilitiesService.imageLinkCreator(x)
});
});
}
}
答案 1 :(得分:0)
playerSearch(text: string): Observable<any[]> {
if (text == "" || !text) {
return Observable.of([]);
} else {
return this.auth.get(`/players?$expand=Contact($expand=Blob)&$filter=contains(Contact/LastName, '${text}') or contains(Contact/FirstName, '${text}')`)
.map((arr: any[]) => {
return arr.map(x => {
debugger;
({
Id: x.Id,
Name: x.Contact.FirstName + " " + x.Contact.FatherName.substring(0, 2) + ". " + x.Contact.LastName,
BlobSrc: this.utilitiesService.imageLinkCreator(x)
})
});
});
}
}
这是我尝试运行的代码,基于你的Amit。我在嵌套的map
中添加了一个调试器,但从未进入。没有实际错误。