简体   繁体   English

angular2中的地图问题

[英]map issue in angular2

I am creating advance login system in angular2. 我正在angular2中创建高级登录系统。 Now i am facing blocker issue. 现在,我面临着阻塞问题。 I have created gateway for api communication in angular2. 我已经在angular2中创建了用于API通信的网关。 This is my code 这是我的代码

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

} If status 200 mean i am able to see status code of response message in console.log. }如果状态为200,则我可以在console.log中看到响应消息的状态代码。 but if i get response as 403 mean i need to process some function in this case i am facing issue i am unable to process those function because i did subscribe error in my component 但是,如果我得到的响应为403,则表示我需要处理某些功能,在这种情况下,我面临问题,因为我确实在组件中订阅了错误,所以无法处理那些功能

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

So please suggest me some idea to trigger function if i get 403 otherwise such as 400 mean need to show message in alert. 因此,如果我得到403,请向我建议一些触发功能的想法,例如400表示需要在警报中显示消息。 This is my token setup, here i am resetting token using set Interval 这是我的令牌设置,这里我使用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);
  }

It's because in the case of a 403 status code, the map callback won't be executed but the catch one (and if not the error callback specified when subscribing). 这是因为在使用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);
      }
    });

I guess that you try to dynamically add the token if you receive a 403 error and execute again the request. 我猜想如果您收到403错误并再次执行请求,则尝试动态添加令牌。

Here is a sample: 这是一个示例:

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

  (...)
}

If you need to make a request to get the auth token you need to leverage the flatMap operator: 如果您需要请求获取auth令牌,则需要利用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);
      }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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