Custom http request returns an error in angular2

2019-09-12 17:07发布

问题:

I have two services

Http client service

 get(url):any{
  this.storage.get('token').then((name) => {
    let headers = new Headers();
    this.createGeneralHeaders(headers);
    return this.http.get(url+"?access-token="+name, {
      headers: headers
    });

});

And then i have this

  constructor( private _httpClient:HttpClient){}

  getTrucks():Observable<any>{
   return this._httpClient.get(this.trucksurl+"phone-trucks")  
       .map(res => res.json().data)  //returns an error

  }

The second service returns an error that cannot read property map of undefined

回答1:

Your get(url) method does not return anything. This is why you are experiencing this problem.

Also note that you should not be specifying the any type. The compiler would have caught this error for you had you let it infer the return type which would have been void but instead you specified the return type as any, short-circuiting the type inference process for no reason.

I realize a lot of angular examples do this but those examples are not examples of good TypeScript code.

Assuming http in your first service is a reference to the official angular 2 http service you would want something like

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/operator/mergeMap';

export class HttpClient {
  get(url: string) {
    const headers = new Headers();
    this.createGeneralHeaders(headers);

    return Observable
      .fromPromise(this.storage.get('token'))
      .flatMap(
        name => this.http.get(`${url}?access-token=${name}`, {headers})
      );
  }
}

In your original code, get was not returning anything, and updating it to return the result of the then call would result in it returning a Promise to an Observable instead an Observable. Since the consuming code was calling map I assume the intention was to return an Observable. This can be achieved by using Observable.fromPromise. Another way would be to return an Observable directly from the storage service but not knowing the internals of that service the above option is simpler.