dyh333
dyh333

Reputation: 395

angular4+ how to change httpClient return body?

I hope the rxjs observable return only data, so I want to use HttpInterceptor to change the HttpResponse's body. the codes are

@Injectable()
export class NodeInterceptor implements HttpInterceptor {
intercept(
  req: HttpRequest<any>,
  next: HttpHandler
): Observable<HttpEvent<any>> {
  return next.handle(req).map(event => {
    if (event instanceof HttpResponse) {
      console.log(event);
      if (event.status === 200) {
        event.body = event.body.result;
      }
    }
    return event;
  });
} }

but show the body cannot be changed, how can i do that?

Upvotes: 0

Views: 485

Answers (1)

Dheeraj Kumar
Dheeraj Kumar

Reputation: 4175

Letting HttpInterceptor do what it is supposed to, You dont need to modify HttpInterceptor to return ResponseMessages in Angular.

This is how you can catch Response Messages from Api im Angular.

In your service.ts

 add(obj: Model): Observable<Model> {

        return this.http
        .post(this.url, item, { responseType: 'text' });

    }

In you component

 this.service.add(this.obj).subscribe(
        (value) => { this.response = value },
        (error) => { },
        () => {

            if (this.response === "Data saved successfully.") {
                // here you receive Response message.
            }

        });

Hope this helps.

Update: You can create a Generic HttpService and call it from all your components.

@Injectable()

export class ApiServices {

url: string;

constructor(private http: HttpClient, config: APIConfig) {

    this.url = config.server + config.apiUrl;

}

public getAll(type: string): Observable<T[]> {

    return this.http
        .get(this.url + type)
            .map((res: any) => res);
}


public get<T>(type:string, id?: number): Observable<T> {

    return this.http
        .get<T>(this.url);
}


public add<T>(type:string, item: T): Observable<any> {

    return this.http
        .post(this.url + type, item, { responseType: 'text' });
}

public update<T>(type: string, item: T): Observable<any> {

    return this.http
        .put(this.url + type, JSON.stringify(item), { responseType: 'text' });
}

public delete<T>(id: number) {

    return this.http
        .delete <T>(this.url);
}

}

Upvotes: 1

Related Questions