gpt4 book ai didi

Angular 4 HttpClientModule 和 map() 函数

转载 作者:太空狗 更新时间:2023-10-29 19:34:07 25 4
gpt4 key购买 nike

我遇到了一个关于新 HttpClientModule 和来自 RX.js 的 map() 函数的问题。

我想做的是更改来自 get() 方法的可观察对象中返回数组的对象。

我当前的代码:

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);

我得到的错误:

Type 'Observable<{ Id: any; Name: string; BlobSrc: string; }>' is not assignable to type 'Observable'.

Type '{ Id: any; Name: string; BlobSrc: string; }' is not assignable to type 'any[]'.

据我所知,map() 方法返回一个 observable,其值只有一个对象而不是一个数组。

为了返回包含 { Id: any; 数组的可观察对象,正确的语法是什么?名称:字符串; BlobSrc:字符串; } 对象?

最佳答案

如果您的 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)
});
});
}
}

关于Angular 4 HttpClientModule 和 map() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45954254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com