【问题标题】:Angular 6 - Update *ngIf after Component LoadsAngular 6 - 组件加载后更新 *ngIf
【发布时间】:2018-08-06 00:57:38
【问题描述】:

组件:

import { Component, OnInit } from '@angular/core';

// Services
import { AuthService } from './services/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit {
  user: Object;
  authorized: boolean;

  constructor(private authService: AuthService) {}

  ngOnInit() {
    this.authorized = this.authService.loggedIn();
  }
}

HTML:

<app-navbar *ngIf="authorized"></app-navbar>

<div id="content"
     *ngIf="authorized">
    <app-sidebar></app-sidebar>

    <div class="wrapper full-width">
        <router-outlet></router-outlet>
    </div>
</div>

<div class="container mt-6"
     *ngIf="!authorized">
    <router-outlet></router-outlet>
</div>

this.authService.loggedIn(); 返回 true 或 false,用于显示 HTML 的 *ngIf 中的一些元素。用户登录后会被重定向到此页面,因此 *ngIf 不会自动读取。相反,您必须刷新页面才能正确更新所有内容。

据我所知,我无法订阅 this.authService.loggedIn(),因为它不是可观察的,所以我不确定当用户第一次查看组件时如何自动更新视图。以下是服务本身供参考:

loggedIn() {
    if (localStorage.id_token === undefined ) {
      return false;
    } else {
      const helper = new JwtHelperService();
      return !helper.isTokenExpired(localStorage.id_token);
    }
  }

【问题讨论】:

    标签: angular angular6


    【解决方案1】:

    您可以通过将 authorized 属性设置为 getter 来确保它是最新的:

    public get authorized(): boolean {
      return this.authService.loggedIn();
    }
    

    【讨论】:

    • 这似乎工作得很好,但它破坏了其他组件的加载。现在,当我尝试导航到另一条路线时,路线本身会更改 HTML 或 内容在我刷新页面之前不会更新。什么可能导致点击的路由内容无法加载?
    • 此代码仅从服务获取当前值。我不知道是什么导致加载问题。可以在控制台中查看是否有报错。
    • 不要使用ngIf来隐藏路由器出口,您可以考虑实现route guard以仅在用户登录时允许导航。
    猜你喜欢
    • 2019-09-02
    • 2019-04-03
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多