Angular 2 如何根据返回的状态代码在 REST http post/put 后​​重定向

标签 angular angular2-routing angular2-services angular2-http

我正在尝试在 http put 请求成功和失败后将其重定向/重新路由到特定页面。 API 根据成功或错误返回一些状态代码(500、401、200 等) 我不知道如何处理这个重定向

我的服务代码如下所示

putCustomer(body: string){
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers, method: 'put', withCredentials: true });

    return this.http.put(this._customerUrl, body, options)
        .map(res => res.json())
        .catch(this.handleError)
        .subscribe();
}
private handleError (error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || ' error');
}

请帮忙。

更新: 对 Fredrik 的答案进行一些细微调整:

import { Injectable } from '@angular/core';
import {Http, Response} from '@angular/http';
import {Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import { Router } from '@angular/router';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';

.........

constructor(private router: Router, private http: Http) { }

      putCustomer(body: string){
            let headers = new Headers({ 'Content-Type': 'application/json' });
            let options = new RequestOptions({ headers: headers, method: 'put', withCredentials: true });

            //alert(body);
            return this.http
            .put(this._customerUrl, body, options)
            .do(res => {
            if(res.status === 200 ||res.status === 201) {
              this.router.navigate(['/success']);
            }
            else if(res.status === 401){
              this.router.navigate(['/error']);
            }
            else if(res.status >= 500){
              this.router.navigate(['/error']);
            }
          })
            .map(res => res.json())
            .catch(this.handleError)
            .subscribe();
        }
        private handleError (error: Response) {
            console.error(error);
            return Observable.throw(error.json().error || ' error');
        }

    }

最佳答案

使用Response.status从http响应中获取状态代码。然后使用 Router.navigate(...) 进行重定向。您可以在 Observable 上使用 do 运算符来执行导航到另一条路线的副作用

片段:

.do(res => {
   if(res.status === '200') this.router.navigate(['/somewhere']);
   else if(......) ...;
 })

与您的代码集成的更完整示例:

import { Router } from '@angular/router'

...

export class YourClass {

  constructor(router: Router, ...) {}

  putCustomer(body: string){

    ...

    return this.http
      .put(this._customerUrl, body, options)
      .do(res => {
        if(res.status === '200') this.router.navigate(['/somewhere']);
        else if(......) ...;
      })
      .map(res => res.json())
      .catch(this.handleError)
      .subscribe();
}

关于Angular 2 如何根据返回的状态代码在 REST http post/put 后​​重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44778789/

相关文章:

angular - 使用 Angular 中的 Pipe 过滤器从数组中过滤唯一元素

angular - 使用 Angular/ typescript 中的另一个函数为接口(interface)属性分配值?

angular - 将自定义指令动态添加到组件中的 ng-template

angular - 在与 parent 相同的路由器 socket 中使用子路由

unit-testing - 测试可观察对象 Angular 2 karma

Angular 6 Jwt拦截器

Angular2 ComponentRouter 防止自动组件重用

javascript - 'router-outlet' 不是 Angular2 的已知元素

javascript - 如何使用 Angular 2 和 TypeScript 在 Promise 中设置变量

angular - 在 Angular 2 服务中测试异步(Promise)方法