【问题标题】:Calling Observable having subscribe inside调用 Observable 并在里面订阅
【发布时间】:2018-11-23 16:56:47
【问题描述】:

我仍然对 Observables 和订阅者有一些问题,我面临的是,如果我从组件中调用 Observable 方法,我没有获得数据。它是未定义的:

login(username: string, password: string): Observable<any> {
       const body =  {
            'Mobile': username,
            'Password': password,
            };
        return this.http.post(`${this.baseURL + this.loginApiRoot}/Login`, body)
            .pipe(map((response: Response) => {
                const jobj = JSON.parse(response.text());
                const loginrequest = jobj['lr'];
                const token = loginrequest['token'];
                const is2auth = loginrequest['authtype'];
                const schoolcode: string[] = jobj['schoolcode'];
                // login successful if there's a jwt token in the response
                if (token && token !== 'Invalid Login' ) {
                    if (token === 'Oops! seems you have not confirmed your email') {
                      return {result: false, message: token};
                    }
                    this.getUserRole(token).subscribe(userRole => {
                      this.userRole = userRole[0];
                      if (this.userRole === 'school' || this.userRole === 'admin') {
                        this.LoginSuccess(token, username, is2auth);
                        // return {result: true, message: token};
                      } else {
                        this.LoginFailed(token, username, is2auth);
                        // return {result: false, message: token};
                      }
                    });
                } else {
                    // return false to indicate failed login
                    this.LoginFailed(token, username, is2auth);
                    return {result: false, message: token};
                }
            }));
    }

调用方法:

this.authenticationService.login(this.model.username, this.model.password)
    .subscribe(
      data => {
        // tslint:disable-next-line:prefer-const
        console.log(data);
        let result = data.result;

这个 console.log 正在返回未定义的数据。

这个来自另一个项目的代码工作正常:

login(username: string, password: string): Observable<any> {        
       var body =  {
            "Email":username,
            "Password":password,
            }          
        return this.http.post(`${this.loginApiRoot}/Login`, body)
            .map((response: Response) => {
                let jobj = JSON.parse(response.text());
                let token = jobj["token"];
                let is2auth=jobj["authtype"];
                // login successful if there's a jwt token in the response
                if (token && token!="Invalid Login" ) {
                    if (token =="Oops! seems you have not confirmed your email"){
                        return {result:false,message:token};
                    }
                    this.token = token;
                    this.isValidUser = true
                    this.userEmail = username;
                    this.setToken(username, token)
                    this.authType=is2auth;
                    if (is2auth==1)
                    {   
                        this.isLogin=true;
                        this.is2Auth=true;
                        this.router.navigate(['/markets']);
                        return {result:true,message:token};
                    }
                    else if (is2auth>1)
                    {
                       this.isLogin = true;
                       this.is2Auth=false;
                       this.router.navigate(['/verify2auth']);
                       return {result:false,message:token};
                    }
                    else
                    {
                    }
                }

                else {
                    // return false to indicate failed login
                    return {result:false,message:token};
                }
            });
    }

【问题讨论】:

    标签: angular observable subscribe ecmascript-2016


    【解决方案1】:

    您应该在您的组件而不是您的服务中进行所有验证,只需从您的服务中返回 observable 并在订阅中进行验证,

     return this.http.post(`${this.baseURL + this.loginApiRoot}/Login`, body)
     .pipe(map((response: Response) => {
        return response;
    }));
    

    在组件中,

    this.authenticationService.login(this.model.username, this.model.password)
        .subscribe(data => {
        let result = data;
         // do all your validations here
    }
    

    您还在第一次调用获取 UserRole 时创建了另一个 http get 方法,您应该在从第一次获取结果后将其作为函数分开。

    【讨论】:

    • 好的,为什么不推荐我这边的方法。请不要我没有阅读任何文档。我只是弄脏我的手。
    • 您返回的是一个对象,而不是您无法订阅的可观察对象
    • 好的,所以如果我以任何方式返回 observable 那么有可能吗?
    • 我不是在争论,而是试图理解,请看我编辑的问题,另一个项目中的代码对我有用。
    • 你在吗?
    【解决方案2】:

    您需要在此行根据您的要求返回一些东西

    if (this.userRole === 'school' || this.userRole === 'admin') {
                            this.LoginSuccess(token, username, is2auth);
                            // return {result: true, message: token};
                          } else {
                            this.LoginFailed(token, username, is2auth);
                            // return {result: false, message: token};
                          }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 2019-12-03
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 2019-12-29
      • 1970-01-01
      相关资源
      最近更新 更多