在我的AuthService
中,我发送错误消息的业务错误
在我的LogInComponent
中,它捕获了该错误但无法显示错误消息"Login failed Error"
,而是在控制台日志中显示了类型对象对象。
为什么这样?如何正确显示错误信息?
import { Injectable } from '@angular/core';
import { Response } from "@angular/http/src/static_response";
import { Http } from "@angular/http";
import { Observable } from "rxjs/Observable";
import { UUID } from "angular2-uuid";
import 'rxjs/Rx'
import { User } from "app/user/user";
import { Subject } from "rxjs/Subject";
@Injectable()
export class AuthService {
REMOTE_USER_URL = "http://localhost:3000/users/";
public subject: Subject<User> = new Subject<User>();
constructor(public http: Http) { }
public get currentUser(): Observable<User> {
return this.subject.asObservable();
}
public login(username, password) {
return this.http.get(this.REMOTE_USER_URL + "?username=" + username)
.map((response: Response) => {
// login successful if there's a jwt token in the response
let data = response.json();
if (data.length == 1) {
let user = data[0];
if (user.username == username && user.password == password) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
this.subject.next(Object.assign({}, user));
return "LoggedIn Successfully";
} else {
console.log("throw login failed Errror **");
//throw Observable.throw(response);
throw Observable.throw(new Error("login failed error "));
}
} else {
console.log("throw login failed Errror ****");
throw Observable.throw(new Error("login failed error "));
}
});
}
logout() {
localStorage.removeItem('currentUser');
this.subject.next(Object.assign({}));
}
}
下面是UserloginComponent
,它捕获抛出错误但不显示错误消息
login() {
this.loading = true;
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(
data => {
this.router.navigate([this.returnUrl]);
},
error => {
// how to get this Error Message
console.log("here is error "+ error);
this.alertService.error(error);
this.loading = false;
});
}
答案 0 :(得分:0)
错误是对象。添加行
console.dir(error);
您将在控制台中获得列出所有属性的对象。您需要在行
中使用错误对象的某些属性console.log("here is error "+ error);
答案 1 :(得分:0)
我发现它现在有问题 我应该使用throw new Error(&#34;它在登录时失败&#34;)而不是 抛出Observable.throw(新错误(&#34;登录失败&#34;));