简体   繁体   中英

Http get method using angular6

Previously my project was on angular2. Now its upgraded to angular6. I am facing some issues regarding the version changes. I will get some json data from an api and I am accessing it through the @angular/http. Following are the angular service I've tried

import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

 constructor(private http: HttpClient, @Inject('api') private serverApi) { }

  public getResultList(): Promise<any> {
    let uri = `${this.serverApi}/list`;
    return this.http.get(uri)
      .toPromise()
      .then((res) => {
        let temp = res.json();
        return { 'statusCode': 200, 'message': 'success', 'result': temp['items'], 'error': {} };
      })
      .catch((error) => {
        return { 'statusCode': 200, 'message': 'failed', 'result': {}, 'error': error };
      })
  }

I would like to replace the above code to angular6. Following are the code I've tried.

import { HttpClient } from '@angular/common/http';

 constructor(private http: HttpClient, @Inject('api') private serverApi) { }


 public getResultList(): Observable<any> {
    let uri = `${this.serverApi}/list`;
    return this.http.get<any[]>(uri)
      .pipe(
      tap((res) => {
        let temp = res;
        return { 'statusCode': 200, 'message': 'success', 'result': temp['items'], 'error': {} };
      }),
      catchError((error) => {
        var data = { 'statusCode': 200, 'message': 'success', 'result': {}, 'error': error };
        this.handleError('getResultList', data)
      })
      );
  }

  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(error); // log to console instead
      return of(result as T);
    };
  }

Here I am getting the response from the server side but not able to customise the get result and return it from the tap itself. Please help me to resolve the same.

Tap is just for actions alongside with the observables, and from the docs:

Tap definition - Transparently perform actions or side-effects, such as logging.


This means that you are actually doing nothing, plus your are not subscribe to the Observable it self. Or if you want to use it as promise you could too, But you still have to do it.

return this.http.get<any[]>(uri)
      .pipe(
      tap(() => {
        console.log("just logging or something");
      }),
      // You have to use map to transform the respond to something else.
      map((res) => { 'statusCode': 200, 'message': 'success', 'result': temp['items'], 'error': {} }),

      catchError((error) => {
        var data = { 'statusCode': 200, 'message': 'success', 'result': {}, 'error': error };
        this.handleError('getResultList', data)
      })
      )

You also may add a map inside the pipe if you want to transform the result to something else.
EDIT--
In you component:

this.service.getResultList()          
.subscribe(
(res) => {
   console.log(res); // <-- Here you can do what ever you want with the result after you subscribe.
},
(err) => {
   console.log(err);
})

You can catch the errors from the subscribe without any problems, then you can handle it in the UI as you wish and also catch the error.

I explained how to return a null from an error() operator. Your code is really. A service should not return the http status code and other header poperties but the real data objects.

Use https://www.npmjs.com/package/class-transformer to convert direcly the json result into real classes. If an error happens then react in the ui.

this.service.getResultList()
.pipe(error(x => {
    return null; // here you return sth to the subscribe
}))
.subscribe(
(res) => {
    if(res == null) return; // then you need to handle this null
    console.log(res); // <-- Here you can do what ever you want with the result after you subscribe.
},
(err) => {
   console.log(err);
})

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM