【问题标题】:How to handle returned data from http request如何处理来自http请求的返回数据
【发布时间】: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


【解决方案1】:

首先,不要使用名为User 的类(我在登录字段上有错误)。例如,将其重命名为 MyUser

你需要在登录函数中使用map而不是subscribe并返回一个Observable&lt;MyUser&gt;

login(username:string, password:string) : Observable<MyUser> {
    return this.getUser(username, password).map(user => {
        if(user.login===username && password===user.password){
            this.isLoggedIn=true;
        }
        return user;
    });
}

getUser(username:string, password:string): Observable<MyUser>{
    return (this.http.get(this.url).map((r) => {
        return r.json() as MyUser;
    })
    .catch(this.handleError))

}

说明: 在 login 函数中,您定义了要链接的操作,但这些操作尚未执行。调用subscribe() 时会执行该链。

首先,您获取用户 (http.get),然后检查登录名/密码。 然后,您只调用一次subscribe()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多