单击Click Me
按钮将调用getDataAsObservable
脚本中定义的http.service.ts
方法:
export class HttpService {
jsonFile = '../assets/products.json';
constructor(private http: HttpClient) {}
getDataAsObservable(): Observable<any> {
return this.http.get(this.jsonFile)
}
}
从observable
服务接收到http
后,在requestDataAndWait
脚本中定义的app.component.ts
方法将接收到的response
分配给局部变量{{1 }},并将其返回给data
方法。但是,onClick
方法不是接收数组数据,而是获取onClick
对象:
ZoneAwarePromise
以下是Stackblitz项目的链接: https://stackblitz.com/edit/angular-ivy-bygaut?file=src%2Fapp%2Fapp.component.ts
如何使 async requestDataAndWait() {
let data = [];
await this.http.getDataAsObservable()
.toPromise().then(response => {data=response;} );
return data
}
返回requestDataAndWait
数组而不是data
对象?
答案 0 :(得分:1)
您需要先更改Service类以返回这样的响应
import Foundation
struct PokemonListResults: Codable {
let results: [PokemonListResult]
}
struct PokemonListResult: Codable {
let name: String
let url: String
}
struct PokemonResult: Codable {
let id: Int
let name: String
let types: [PokemonTypeEntry]
}
struct PokemonTypeEntry: Codable {
let slot: Int
let type: PokemonType
}
struct PokemonType: Codable {
let name: String
}
struct PokemonImage: Codable {
let sprites: sprite
}
struct sprite: Codable {
let front_default: String
}
struct descriptions: Codable {
let flavor_text_entries: [items]
}
struct items: Codable {
let flavor_text: String
let lang: language
}
struct language: Codable {
let name: String
}
然后像这样更改您的组件类
getDataAsObservable(): Promise<any> {
return this.http.get(this.jsonFile).toPromise()
}