自定义http请求在angular2中返回错误 [英] Custom http request returns an error in angular2

查看:48
本文介绍了自定义http请求在angular2中返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两项服务

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
    });

});

然后我有这个

  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

推荐答案

您的 get(url)方法不返回任何内容.这就是为什么您遇到此问题的原因.

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

还请注意,您应该 指定 any 类型.如果您让编译器推断返回类型为 void 的返回类型,但您将返回类型指定为 any ,则会使该错误发生,从而使类型推断过程无缘无故.

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.

我意识到有很多角度的例子可以做到这一点,但是这些例子并不是好的TypeScript代码的例子.

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

假设您的第一项服务中的 http 是对您想要的官方angular 2 http服务的引用

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})
      );
  }
}

在您的原始代码中, get 未返回任何内容,并且对其进行更新以返回 then 调用的结果将导致其返回 Promise 改为 Observable .由于使用方代码正在调用 map ,因此我认为这样做的目的是返回一个 Observable .这可以通过使用 Observable.fromPromise 来实现.另一种方法是直接从存储服务返回 Observable ,但不知道该服务的内部,上面的选项更简单.

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.

这篇关于自定义http请求在angular2中返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆