Home > OS >  i cant fix the .map on http post client
i cant fix the .map on http post client

Time:12-02

public postForObjecty(endpoint: any, data: any) {
        return new Promise((resolve, reject) => {
            let url = this.createBasicUrl(endpoint);
            let _data = this.arrangeData(data);
            let headers: any = new Headers()
            let token = `Bearer ${RestProvider.BEARER_TOKEN}`;
            headers.append('Authorization', token);
            this.http.post(url, _data, { headers: headers })
                .map((res: { json: () => any; }) => res.json())
                .subscribe((data: unknown) => {
                    resolve(data);
                }, (err: any) => {
                    reject(err);
                });
        });
    }

i want to post and get methond to backend but i cant fix this code

.map

this doesnt work,

if i could fix this .map method it will be done

CodePudding user response:

You want to use RxJS map method. For that you need to .pipe the observable stream like so:

  public postForObjecty(endpoint: any, data: any) {
    return new Promise((resolve, reject) => {
      let url = this.createBasicUrl(endpoint);
      let _data = this.arrangeData(data);
      let headers: any = new Headers()
      let token = `Bearer ${RestProvider.BEARER_TOKEN}`;
      headers.append('Authorization', token);
      this.http.post(url, _data, { headers: headers })
        .pipe(map((res: { json: () => any; }) => res.json()))
        .subscribe((data: unknown) => {
          resolve(data);
        }, (err: any) => {
          reject(err);
        });
    });
  }

CodePudding user response:

By default the Angular HttpClient will handle processing the JSON response for you. Assuming you are using this service, this means your map here is not necessary and can be removed entirely.

public postForObjecty(endpoint: any, data: any) {
    return new Promise((resolve, reject) => {
      let url = this.createBasicUrl(endpoint);
      let _data = this.arrangeData(data);
      let headers: any = new Headers()
      let token = `Bearer ${RestProvider.BEARER_TOKEN}`;
      headers.append('Authorization', token);
      this.http.post(url, _data, { headers: headers })
        .subscribe((data: unknown) => {
          resolve(data);
        }, (err: any) => {
          reject(err);
        });
    });
  }

If you do need the full response, such as the HTTP status code you can pass observe: 'response' into the options object the post function accepts. The Angular documentation goes into good detail on this.

As an FYI, in older versions of Angular that had a now deprecated service called Http and you would need to call .json() all the time.

  • Related