Home > Software engineering >  Angular return [object Object]
Angular return [object Object]

Time:12-17

I'm trying to send a post request. But the API returns undefined, and I send it to my API, as it turned out [object Object]

getAccouting():Observable<any>{
    // let json = this.http.get<any>('/assets/cities/altayskiy_kray/accounting.json'); if i use it json return undefined
    let json;
    this.http.get('/assets/cities/altayskiy_kray/accounting.json').pipe(data=>json=data);
    let formData:FormData = new FormData;
    formData.append('json', json);
    return this.http.post<any>('http://api/api.php', formData);
  }

How fix that?

CodePudding user response:

http.get is async so it will not have emitted before you return the http.post. Therefore, json will be undefined.

Instead you can chain them and return the whole observable:

getAccouting(): Observable<any>{
  return this.http.get('/assets/cities/altayskiy_kray/accounting.json').pipe(
    switchMap(json => {
      return this.http.post<any>('http://api/api.php', json);
    }
  );
}

Do you need to use FormData? If you append the json object then you will get its string value: [object Object].

You could stringify the json object, but you will have to decode it on the server:

formData.append('json', JSON.stringify(json))
  • Related