我正在尝试将其重定向/将其重新连接到成功之后,并在我的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');
}
请帮助。
更新:对弗雷德里克答案的一些小调整:
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(...)
重定向。您可以在可观察的上使用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();
}
只是导入路由器
import { Router } from '@angular/router';
然后将其注入构造函数:
constructor(private router: Router) {}
然后使用路由器进行重定向
this.router.navigate(['/nextPage']);