首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >angular中的嵌套订阅

angular中的嵌套订阅
EN

Stack Overflow用户
提问于 2021-07-11 17:50:11
回答 1查看 86关注 0票数 0

这是我的代码..我需要检查2个可观测数据..it对1个可观测数据有效如何检查另一个可观测数据

代码语言:javascript
运行
复制
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, CanActivateChild, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { filter, map, take } from 'rxjs/operators'
import { AuthenticationService } from '../services/authentication.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate  {

  constructor(private authService: AuthenticationService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):  Observable<boolean> | Promise<boolean> | boolean
  {
    
    return this.authService.isAuthenticated.pipe(
      filter(val => val !== null), // Filter out initial Behaviour subject value
      take(1), // Otherwise the Observable doesn't complete!
      map(isAuthenticated => {
        if (isAuthenticated) {  

  TRY 1...........Initial code with direct access without observable but it is not working after login it is not navigate ..if i refresh (f5) then this works
     if( state.url !== '/changepassword'   &&  this.authService.getUserValue.changePassword)
               this.router.navigateByUrl('/changepassword');               
                return true;
----------------------------------------------

         // TRY 2 //Added conditional if 
          -----------------------------------------------------------
           ///i need to subscibe another value and if value is true the route to change 
            password else dashboard should load
           this.authService.getUserValueObs().pipe(
            filter(val => val !== null), // Filter out initial Behaviour subject value
            take(1),
            map(user =>{
                if( state.url !== '/changepassword'   &&  user.changePassword)
                    this.router.navigateByUrl('/changepassword'); 
                }
             ));
            ----------------------------------------------------
           return true;   // i need to retun this value after subscibe of inner observble...
        } else {          
          this.router.navigateByUrl('/')
          return false;
        }
      })
    );
  }
}

目前的AuthGuard代码运行良好,但我需要添加另一个条件,如果订阅的值,而不是仪表板更改密码页面应加载?如何做多订阅方法

编辑:

这是我的身份验证服务类*方法。

代码语言:javascript
运行
复制
 export class AuthenticationService {
 
   isAuthenticated: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null);
 
   userSubject$= new  BehaviorSubject<IAuthenticatedUser>(undefined);

  get getUserValue(): any  {
    return this.userSubject$.value;
  }

  getUserValueObs(): Observable<IAuthenticatedUser>  {
    return this.userSubject$.asObservable();
  }

      login(credentials: {userName:string, password:string}): Observable<any> {
            return this.http.post(`${baseUrl}/authenticate-app`, credentials).pipe(
               map((result: any) => result.data),
               switchMap((user: {userId,userName, fullName refreshToken}) => { 
                if(user)
                    return this.storeUserData(user);
                 }
                  
              }), 
              tap(_ => {
                this.isAuthenticated.next(true);
              })
            )

}

当前问题是,当登录时,我正在为两个行为赋值通过我们的subject...but Ispasswordchange更改一段时间未获得value..if我刷新然后值到来

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-11 18:20:53

如果要从一个可观测对象切换到另一个可观测对象,并使用前一个可观测对象中的值,可以使用switchMap运算符:

代码语言:javascript
运行
复制
return this.authService.isAuthenticated.pipe(
  filter((val) => val !== null), // Filter out initial Behaviour subject value
  take(1), // Otherwise the Observable doesn't complete!
  switchMap((isAuthenticated) => {
    if (isAuthenticated) {
      return this.authService.getUserValueObs().pipe(
        filter((val) => val !== null), // Filter out initial Behaviour subject value
        take(1),
        map((user) => {
          if (state.url !== "/changepassword" && user.changePassword)
            return this.router.navigateByUrl("/changepassword");
          return true;
        })
      );
    } else {
      return this.router.navigateByUrl("/");
    }
  })
);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68335107

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档