我正在尝试在 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/