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:
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 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:
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.