[英]get http request executing before put request although I used async await
I am trying to execute the put request before the get request, by using async and await, but the put executes after the get, Can someone help please.我正在尝试通过使用异步和等待在获取请求之前执行放置请求,但是放置在获取之后执行,有人可以帮忙吗? Here is my code:这是我的代码:
export class DataStorageService {
constructor(private dataservice: DataServiceService, private http: HttpClient) {}
storeData() {
const movies = this.dataservice.Movies;
this.http.put('https://my-movies-1f9a9.firebaseio.com/movies.json', movies).subscribe(
responseData => {
console.log(responseData);
return responseData;
}
)
}
fetchData() {
let movies: IMovie[];
this.http.get < IMovie[] > ('https://my-movies-1f9a9.firebaseio.com/movies.json').subscribe(
responseData => {
movies = responseData;
console.log(movies);
}
)
}
async asyncCall() {
await this.datastorageservice.storeData();
this.datastorageservice.fetchData();
}
It looks like subscribe
is not necessary here as you want to use async
and await
keywords:看起来这里不需要subscribe
,因为您想使用async
和await
关键字:
export class DataStorageService {
constructor(private dataservice:DataServiceService, private http:HttpClient) { }
storeData(){
const movies=this.dataservice.Movies;
this.http.put('https://my-movies-1f9a9.firebaseio.com/movies.json', movies)
}
fetchData(){
let movies:IMovie[];
this.http.get<IMovie[]>('https://my-movies-1f9a9.firebaseio.com/movies.json')
}
}
and then you can use async
and await
:然后你可以使用async
和await
:
async asyncCall() {
let result = await this.datastorageservice.storeData();
let anotherResult = this.datastorageservice.fetchData();
}
If your service return Observable
, then you need to to call toPromise()
method:如果您的服务返回Observable
,那么您需要调用toPromise()
方法:
async asyncCall() {
let result = await this.datastorageservice.storeData().toPromise();
let anotherResult = this.datastorageservice.fetchData().toPromise();
}
Try to set your http request a promise, personally I separate http requests in a service for example:尝试将您的 http 请求设置为 promise,我个人在服务中将 http 请求分开:
file.service:文件服务:
async getData(): Promise<any> {
const url = 'http://myrestservice';
This.http.get(url,{Headers, observe: 'response' }).pipe(map((resp: any) => {
return resp;
})).toPromise();
}
file.component:文件组件:
const request: any = await this.requestServ.getData().then((resp) => resp).catch((err) => err);
I hope it is useful for you我希望它对你有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.