【问题标题】:map issue in angular2angular2中的地图问题
【发布时间】:2016-04-21 06:57:56
【问题描述】:

我正在 angular2 中创建高级登录系统。现在我面临拦截器问题。我在 angular2 中创建了用于 api 通信的网关。这是我的代码

gateWay(Method, Url, data) {
    console.log("gateWay  "+Method)
    this.Method = Method
    this.Url = Url
    this.data = data
    if(Method == "get"){
      return this.http.get('http://localhost:3000/' + Url, { headers: this.insertAuthToken }).map((res) => res.json())
                  .map((res) => res.json())
    }else if(Method == "post"){
      return this.http.post('http://localhost:3000/' + Url, JSON.stringify(data), { headers: this.insertAuthToken })
        .map((res) => res.json());
    }else if(Method == "put"){
      return this.http.put('http://localhost:3000/' + Url, JSON.stringify(data), { headers: this.insertAuthToken })
        .map((res) => res.json());
    }else if(Method == "delete"){
      return this.http.delete('http://localhost:3000/' + Url, { headers: this.insertAuthToken })
        .map((res) => res.json());
    }

} 如果状态 200 意味着我可以在 console.log 中看到响应消息的状态代码。但是如果我得到 403 的响应意味着在这种情况下我需要处理一些功能,我面临的问题是我无法处理这些功能,因为我确实在我的组件中订阅了错误

this.httpService.gateWay('get', 'v1/users/index', undefined)
           .subscribe(
                data => console.log(data),
                error => console.log(error),
                () => console.log("finished")
            )

所以如果我得到 403,请建议我一些触发功能的想法,否则例如 400 意味着需要在警报中显示消息。这是我的令牌设置,这里我使用 set Interval 重置令牌

SetTokenDynamically(time) {
    console.log("time " + time)
    clearInterval(this.timer)
    this.timer = setInterval(() => {
      // this.http.get('https://jsonblob.com/api/jsonBlob/56d80451e4b01190df528171')
      this.http.get('http://localhost:3000/v1/users/tokenUpdate', { headers: this.headerRefreshToken })
        .map((res) => res.json())
        .subscribe(
        data => {
          Cookie.setCookie('Token2', data.token + this.a)
          console.log("Call " + this.a)
          this.response = data;
        },
        error => console.log(error),
        () => {

          console.log(this.response)

          this.insertAuthToken = new Headers({
            'AuthToken': this.response.token || ""
          })
          Cookie.setCookie('Authorization', this.response.token)
          this.SetTokenDynamically(this.response.time_expiry_sec)

        }
        );
    }, time);
  }

【问题讨论】:

    标签: angular angular2-services


    【解决方案1】:

    这是因为在 403 状态码的情况下,不会执行 map 回调,而是执行 catch 一个(如果不是订阅时指定的错误回调)。

    this.http.get('http://localhost:3000/' + Url, {
       headers: this.insertAuthToken
    })
        .map((res) => res.json())
        .catch((res) => { // <------
          if(res.status == 403){
            this.SetTokenDynamically(100);
          }
        });
    

    如果您收到 403 错误并再次执行请求,我猜您尝试动态添加令牌。

    这是一个示例:

    @Injectable()
    export class CustomHttp extends Http {
      constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
        super(backend, defaultOptions);
      }
    
      request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        (...)
      }
    
      get(url: string, options?: RequestOptionsArgs): Observable<Response> {
        console.log('get...');
        return super.get(url, options).catch(res => {
          if (res.status === 403) {
            // Set token in options
            return super.get(url, options);
          } else {
            Observable.throw(res);
          }
        });
      }
    
      (...)
    }
    

    如果您需要发出请求以获取身份验证令牌,则需要利用 flatMap 运算符:

    get(url: string, options?: RequestOptionsArgs): Observable<Response> {
      return super.get(url, options).catch(res => {
        if (res.status === 403) {
            return this.getToken().flatMap(token => {
              // Set token in options
              this.setToken(options);
              // Execute again the request
              return super.get(url, options);
            }
          } else {
            Observable.throw(res);
          }
        });
    

    【讨论】:

    • 得到错误(112,16): error TS2345: Argument of type '(res: any) =&gt; void' is not assignable to parameter of type '(err: any, source: Observable&lt;void&gt;, caught: Observable&lt;any&gt;) =&gt; Observable&lt;any&gt;'. Type 'void' is not assignable to type 'Observable&lt;any&gt;'.
    • 我认为错误是针对 catch 运算符的。你如何定义它?当然!随时告诉我;-)
    • 在放置此import 'rxjs/add/operator/catch'; 错误后得到修复。但现在我收到新错误 flatMap is not a function。你能提一下它的路径吗
    • 你需要导入这个:import 'rxjs/Rx';
    • 仍然得到 error TS2339: Property 'flatMap' does not exist on type 'Subscription' 并且 flatMap 不是函数
    猜你喜欢
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    相关资源
    最近更新 更多