我的角度项目版本6出现问题。我必须在Angular6版本中编写此代码。
出什么问题了,这对您有帮助
版本Angular4
login(user: User){
let url = 'http://localhost:3000/login';
return this.http.post<any>(url, user).map(res => {
this.guardStorage(res.id, res.token, res.user, res.menu);
return true;
}).catch(error => {
console.log(err);
return Observable.throw(err);
});
}
版本Angular6
login(user: User){
let url = 'http://localhost:3000/login';
return this.http.post<any>(url, user).pipe(map(res => {
this.guardStorage(res.id, res.token, res.user, res.menu);
return true;
}),
catchError(error => console.log(error))
);
}
答案 0 :(得分:0)
login(user: User): Observable<any>{
let url = 'http://localhost:3000/login';
return this.http.post(url, user).pipe(
map(res => {
this.guardStorage(res.id, res.token, res.user, res.menu);
return true;
}),
catchError((error: HttpErrorResponse) => {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'login
is..';
console.error("Response Error :: " + errMsg);
return Observable.throw(errMsg); <---- check here
})
)
}
or,
login(user: User): Observable<any>{
let url = 'http://localhost:3000/login';
return this.http.post(url, user).pipe(
map(this.extractData),
catchError((error: HttpErrorResponse) => {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'login
is..';
console.error("Response Error :: " + errMsg);
return Observable.throw(errMsg); <---- check here
})
)
}
private extractData(res: Response) {
let body = res;
console.warn("Response:: " + JSON.stringify(body)); <-- check response
return body || [];
}
答案 1 :(得分:0)
您需要通过catchError函数返回可观察
import {throwError } from 'rxjs';
login(user: User){
let url = 'http://localhost:3000/login';
return this.http.post<any>(url, user).pipe(map(res => {
this.guardStorage(res.id, res.token, res.user, res.menu);
return true;
}),
catchError(error => throwError(error))
);
}