Angular 如何更改JSON返回的数据?
我正在使用OMDB api(在线电影数据库)。我已经创建了一个返回预期数据类型的接口。当通过http get方法请求数据时,返回的数据是:{Search:Array(10),totalResults:“31”,Response:“True”}。我需要的数据在搜索数组中。订阅时,我使用res.Search访问此信息:subscribe((res)=>{res=this.movieResults=res.Search;但是错误显示我的界面上不存在搜索。我如何修复此问题 /*我的界面*/Angular 如何更改JSON返回的数据?,angular,rxjs,angular2-observables,Angular,Rxjs,Angular2 Observables,我正在使用OMDB api(在线电影数据库)。我已经创建了一个返回预期数据类型的接口。当通过http get方法请求数据时,返回的数据是:{Search:Array(10),totalResults:“31”,Response:“True”}。我需要的数据在搜索数组中。订阅时,我使用res.Search访问此信息:subscribe((res)=>{res=this.movieResults=res.Search;但是错误显示我的界面上不存在搜索。我如何修复此问题 /*我的界面*/ export
export interface SearchInterface {
Poster: string;
Title: string;
Type: string;
Year: string;
imdbID: string;
}
导出默认搜索界面
/*我的服务中的get方法*/
searchFilm(name: string): Observable<SearchInterface> {
return this.http.get<SearchInterface>(this.searchUrl + this.apiKey + '&s=' + name);
}
因为您的SearchInterface包含密钥
Poster: string;
Title: string;
Type: string;
Year: string;
imdbID: string;
但您的数据包含密钥
Search: Array(10),
totalResults: "31",
Response: "True"
你可以做一件事-
searchFilm(name: string): Observable<any> {
return this.http.get<any>(this.searchUrl + this.apiKey + '&s=' + name);
}
这里涉及两种数据结构:外部数据结构,由http服务返回,您在问题中描述了:
interface ActualResponse {
Search: Array<SearchInterface>;
totalResults: string;
Response: string;
}
@Amitk88为什么要导出SearchInterface两次
导出接口搜索接口
导出默认搜索界面;
也不要像这样分配变量
res=this.movieResults=res.Search;
getData(event) {
const film = event.target.value;
this.data.searchFilm(film)
.subscribe( (res: SearchInterface ) => {
console.log(res)
});
}
检查您返回的响应。我不认为搜索是界面中的一个键,但您希望在响应中找到搜索。
如果您希望搜索成为响应中的一个键,那么请将其包含在界面下我正在创建一个stackblitz,这里我们已经给出了3个答案:) @JB Nizet的回应非常优雅,这也是我的建议。无论如何,以下是我的贡献: //随机服务
searchFilm(name: string): Observable<SearchInterface[]> {
return this.http.get<ServerResponse>(this.searchUrl + this.apiKey + '&s=' + name).pipe(
map(res => res.Search)
);
}
//ramdom.model.ts
export interface SearchInterface {
Poster: string;
Title: string;
Type: string;
Year: string;
imdbID: string;
}
export interface ServerResponse
{Search: SearchInterface[], totalResults: number, Response: boolean}
感谢您的回复,非常感谢:-)感谢您指出这些问题,非常感谢:-)
getData(event) {
const film = event.target.value;
this.data.searchFilm(film)
.subscribe( (res: SearchInterface ) => {
console.log(res)
});
}
searchFilm(name: string): Observable<SearchInterface[]> {
return this.http.get<ServerResponse>(this.searchUrl + this.apiKey + '&s=' + name).pipe(
map(res => res.Search)
);
}
getData(event) {
const film = event.target.value;
this.searchFilm(film)
.subscribe( (res) => {
/** Sort out res.Search issue */
// res = this.movieResults = res.Search;
this.movieResults = res;
console.log(res);
});
}
export interface SearchInterface {
Poster: string;
Title: string;
Type: string;
Year: string;
imdbID: string;
}
export interface ServerResponse
{Search: SearchInterface[], totalResults: number, Response: boolean}