【发布时间】:2018-08-26 20:31:10
【问题描述】:
我正在尝试订阅一个尝试使用以下对象访问 REST 后端的服务。
export class Country {
iso: String;
iso3: String;
name: String;
niceName: String;
numCode: number;
phoneCode: number;
constructor(values: Country = {}) {
Object.assign(this, values);
}
}
这是从API中获取数据的服务方法,数据被成功获取到map()函数中。
public getCountries(): Observable<Country[]> {
return this.http.get(COUNTRY_URL).pipe(
map(response => {
const countries = response.json()._embedded.countries;
return countries.map((country) => { new Country(country) });
}),
catchError(this.handleError)
);
}
这是订阅服务的消费者。
countries: Country[] = [];
constructor(private countryService: CountryService) {
countryService.getCountries()
.subscribe(countries => {
this.countries = countries;
});
}
country 变量最终成为 undefined 对象的数组。
其他信息
我正在使用 Angular 6 和 RXJS6 并遵循迁移 指导 here
这是一个示例 API 响应。
{
"_embedded" : {
"countries" : [ ... ]
},
"_links" : {
"first" : {
"href" : "http://localhost:8080/api/countries?page=0&size=20"
},
"self" : {
"href" : "http://localhost:8080/api/countries{?page,size,sort}",
"templated" : true
},
"next" : {
"href" : "http://localhost:8080/api/countries?page=1&size=20"
},
"last" : {
"href" : "http://localhost:8080/api/countries?page=11&size=20"
},
"profile" : {
"href" : "http://localhost:8080/api/profile/countries"
},
"search" : {
"href" : "http://localhost:8080/api/countries/search"
}
},
"page" : {
"size" : 20,
"totalElements" : 239,
"totalPages" : 12,
"number" : 0
}
}
任何人都可以看到我的代码有任何问题吗?任何帮助将不胜感激。
【问题讨论】:
-
如果你使用 Angular6 那么你不应该做
response.json()这样的事情 -
有什么解决方法吗?
-
看看
response是什么 -
不应该反过来吗?
Object.assign(this, values); -
结果相同。事实上,从
values分配单个字段会产生相同的结果。这可能与RXJS6.0中的订阅更改有关,但我不确定出了什么问题。
标签: angular typescript rxjs6