Вызов Observable с подпиской внутри

У меня все еще есть некоторые проблемы с 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};
                }
            });
    }

2 ответа

Решение

Вы должны выполнить все проверки внутри вашего компонента, а не в вашем сервисе, просто вернуть наблюдаемое из вашего сервиса и выполнить проверку внутри подписки,

 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
}

Кроме того, вы делаете другой http get-метод внутри вашего первого вызова для получения UserRole, вы должны отделить его как функцию после того, как вы получите reuslt от первого.

Вы должны вернуть что-то на основе ваших требований в этой строке

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};
                      }
Другие вопросы по тегам