我正在尝试使用rxjs map从响应中获取字符串数组。
响应是具有guid
和name
属性的对象数组。
当我得到完整回复时:
public getAllSolutions(): Observable<string[]> {
return this.http.get(`${this.baseUrl}/Solution/All`)
.map((results: Response) => results.json())
}
并使用以下内容输出:
this.solutionsService.getAllSolutions().subscribe(
data => {
console.log(data);
}
);
我明白了:
[
{guid:"6e3d4646e1ad6d78bd225d2bdb5a14709c12e8280796a3b4f27536e8aaaf89ed", name: "Solution 1"},
{guid: "737f838cc457d833ff1dc01980aa56e9661304a26e33885defe995487e3306e7", name: "Solution 2"}
]
我想要的是一个只包含
的数组name
以下文档应该可行:
public getAllSolutions(): Observable<string[]> {
return this.http.get(`${this.baseUrl}/Solution/All`)
.map((results: Response) => results.json())
.map(solutions => solutions.name);
}
但我获得的输出是undefined
。我在这做错了什么?
答案 0 :(得分:2)
让我给你一个完全更正的例子,因为你的回报值甚至没有为你给出的值正确定义,即使它是你所期望的。以下是您的代码的更正版本:
/* This is your response example from your API (as per your comments) that is generated when you run the response.json() function in the Observable mapper:
*
* [
* {guid:"6e3d4646e1ad6d78bd225d2bdb5a14709c12e8280796a3b4f27536e8aaaf89ed", name: "Solution 1"},
* {guid: "737f838cc457d833ff1dc01980aa56e9661304a26e33885defe995487e3306e7", name: "Solution 2"}
* ]
*/
// Define this interface outside of your class to make it easier to reason in your code, regardless of the function below that you choose. You can even put this interface into a different file, if you wish to do so.
interface Solution {
guid: string;
name: string;
}
// This should be the function, assuming RxJS (v4) and @angular HttpModule (v2-4):
public getAllSolutions(): Observable<string[]> {
return this.http.get(`${this.baseUrl}/Solution/All`)
.map((results: Response) => <Solution[]>results.json())
.map((solutions: Solutions[]) => solutions.map((solution: Solution) => <string>solution.name));
}
// This should be the function, assuming RxJS (v5) and @angular HttpClientModule (v5+ currently):
// You need to import the map function from RxJS or else you will get all kinds of stupid errors that don't actually tell you that you need to include this function. This import is also case-sensitive. Fun times.
include { map } from 'rxjs/operators';
public getAllSolutions(): Observable<string[]> {
return this.http.get(`${this.baseUrl}/Solution/All`)
.pipe(
map((response: Solution[]) => response.map((solution: Solution) => <string>solution.name))
);
}
&#13;
[
{guid:"6e3d4646e1ad6d78bd225d2bdb5a14709c12e8280796a3b4f27536e8aaaf89ed", name: "Solution 1"},
{guid: "737f838cc457d833ff1dc01980aa56e9661304a26e33885defe995487e3306e7", name: "Solution 2"}
]
What i would like to have is an array just containing name
Following documentation this should work:
public getAllSolutions(): Observable<string[]> {
return this.http.get(`${this.baseUrl}/Solution/All`)
.map((results: Response) => results.json())
.map(solutions => solutions.name);
}
&#13;