【问题标题】:Reference to component, rendered in "app.component.html"对组件的引用,在“app.component.html”中呈现
【发布时间】:2021-12-10 08:02:16
【问题描述】:

我有一个组件,名为NavigationBar,放在app.component.html中

<body>
<app-navigation-bar></app-navigation-bar>
<router-outlet></router-outlet>
</body>
</html>

他有财产,名为IsUserLogged。如果为 true - 则为登录渲染菜单,如果不是使用登录选项渲染菜单。这有可能从另一个人那里获得对该组件的访问/引用吗? 我已将端点/login 路由到LoginFormComponent。用户登录成功后,我需要将NavigationBar 中的IsUserLogged 更改为true。

【问题讨论】:

    标签: angular angular-components


    【解决方案1】:

    有不同的选项可以得到相同的结果。 我将与您分享其中之一。

    首先,您必须创建一个全局服务

    AuthService.service.ts

    @Injectable({
      providedIn: 'root'
    })
    export class AuthServiceService {
    
      private _sesionState: BehaviorSubject<boolean>;
    
      constructor() {
        this._sesionState = new BehaviorSubject(false)
       }
    
      public changeLoggedIn(isLoggedIn: boolean): void{
        this._sesionState.next(isLoggedIn);
      }
    
      public onLoggedInChanged(){
        return this._sesionState.asObservable();
      }
    
    }
    

    然后,例如在您的登录页面中。

    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css']
    })
    export class LoginComponent implements OnInit {
      
      constructor(private authService: AuthServiceService) {}
    
    
      public login(): void {
        // Your logic here
        // If gets a success login
        this.authService.changeLoggedIn(true);
    
      }
    

    终于在你的导航栏组件中

    @Component({
      selector: 'app-navbar',
      templateUrl: './navbar.component.html',
      styleUrls: ['./navbar.component.css']
    })
    export class NavbarComponent implements OnInit {
      
      constructor(private authService: AuthServiceService) {}
    
    
      public getLoggedInUser(): void {
        this.authService.onLoggedInChanged().subscribe((loggedIn: boolean) => {
          // If(loggedIn) => 
        })
    
      }
    

    在这种情况下,我们使用主题来共享应用程序周围的信息。它可以是任何你想要的,任何类型的数据类型。 因此,如果您想了解更多潜在的主题 我会推荐你​​Subjects, BehaviorSubjects, ReplySubjects

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-16
      • 2021-05-28
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      相关资源
      最近更新 更多