【发布时间】:2017-03-20 20:48:35
【问题描述】:
我是 Angular.io 的新手,在处理来自 http 请求的响应时遇到问题。 我正在尝试制作简单的登录组件。
我写了简单的服务:
@Injectable()
export class AuthService {
private url ='http://localhost:3000/user/1';
constructor(private http: Http){}
isLoggedIn: boolean = false;
user : User;
errorMessage:any;
login(username:string, password:string) {
this.getUser(username, password).subscribe((user)=>{
if(user.login===username && password===user.password){
this.isLoggedIn=true;
}
})
}
logout(): void {
this.isLoggedIn = false;
}
getUser(username:string, password:string): Observable<User>{
return (this.http.get(this.url)
.map(this.extractData)
.catch(this.handleError))
}
private extractData(res: Response){
let body = res.json();
return body || {};
}
private handleError (error: Response | any) {
// In a real world app, you might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
以及调用此服务的登录组件:
public Dologin() {
this.message = 'Trying to log in ...';
this.authService.login(this.model.username, this.model.password)
.subscribe(() => {
this.setMessage();
if (this.authService.isLoggedIn) {
let redirect = '/main';
let navigationExtras: NavigationExtras = {
preserveQueryParams: true,
preserveFragment: true
};
// Redirect the user
this.router.navigate([redirect], navigationExtras);
}
});
}
如您所见,我已经在身份验证服务上使用 Observable,因为我需要检查登录名和密码。现在如何修改我的 Dologin 方法以调用登录等待查询结束?喜欢订阅,但没有 Observable 了
【问题讨论】:
-
您的登录 api 应该返回什么有效/无效凭据?在此基础上,您可以设置标志
-
我修改了我的问题。如果凭证有效,则 isLoggedIn 设置为 true。如果不是,则默认保留(false)
-
从技术上讲这是错误的,你不能比较用户并在前端传递
-
对我来说没关系。假设 GetUser 如果有效则返回 1,如果无效则返回 0。然后在“登录”中,我将使用该 observable 来检查它是 1 还是 0。问题是一样的
标签: angular angular2-observables