当变量发生变化时,NgIf不会更新

Daa*_*v z 6 service typescript angular-ng-if angular

是的,所以我有一个包含以下模板的标题组件(navbar):

<ng-template [ngIf] = "authService.isAuthenticated()">
  <li>
    <a routerLink="Landing" class="navbar-brand" (click)="Logout()"><span class="xvrfont">Logout</span><i class="fa fa-sign-in" aria-hidden="true"></i></a>
  </li>
  <li>
    <a routerLink="Profile" class="navbar-brand"><span class="xvrfont">{{authService.getUsername()}}</span><i class="fa fa-user-circle" aria-hidden="true"></i></a>
  </li>
</ng-template>
Run Code Online (Sandbox Code Playgroud)

当用户通过身份验证时,导航的这一部分应该是可见的.找出它通过authService检查.

要检查用户是否已通过身份验证,将在每次路由更改时运行以下代码:

checkAuthenticated(){
   if  (localStorage.getItem('token') != null){ this.authenticated = true; }
   else { this.authenticated = false; }
   console.log(this.authenticated); // for Debugging. 
}
Run Code Online (Sandbox Code Playgroud)

NgIf语句调用此方法:

public isAuthenticated(){
     return this.authenticated;
}
Run Code Online (Sandbox Code Playgroud)

根据日志,"证实" 真假之间切换正确,但Ngif不响应的变化不知何故.

标头component.ts看起来像这样:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import {AuthService} from "../auth/auth.service";

@Component({
  selector: 'app-header',
  providers: [AuthService],
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class HeaderComponent implements OnInit {

  constructor(private authService: AuthService) { }

  ngOnInit() {
  }

  Logout(){
    this.authService.Logout();
  }

}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.谢谢.

编辑:

auth.service.ts:

import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Router} from "@angular/router";
import 'rxjs/add/operator/map';

@Injectable()
export class AuthService {

  public apiroot = 'http://localhost:3100/';
  public loginResponseMessage = '';
  public registerResponseMessage = '';
  public authenticated = false;


  public constructor(private http: HttpClient,
                     private router: Router) {

  }



  SignUp(username: string, password: string) {
    const User = JSON.stringify({username: username, password: password});
    let response: any;
    this.http.post(this.apiroot + 'register', User, {headers: new HttpHeaders()
      .set('content-type', 'application/json; charset=utf-8')})
      .subscribe(res => {
        response = res;
        this.registerResponseMessage = response.message;
        console.log(this.registerResponseMessage);
      });
  }

  Login(username: string, password: string) {
    const User = JSON.stringify({username: username, password: password});
    let response: any;
    this.http.post(this.apiroot + 'authenticate', User, {headers: new HttpHeaders()
      .set('content-type', 'application/json; charset=utf-8')})
      .subscribe(res => {
        response = res;
        this.loginResponseMessage = response.message;
        if (response.token) {
          localStorage.setItem('token', response.token);
          this.authenticated = true;
          localStorage.setItem('user', response.username);
          this.router.navigate(['/']);
        }
        else{  /* Do Nothing */  }
      });
  }


  Logout(): void{
    this.authenticated = false;
    localStorage.removeItem('token');
    console.log(this.isAuthenticated());
    this.router.navigate(['/Landing']);
  }

  isAuthenticated(){
    return this.authenticated;
  }

  checkAuthenticated(){
    if  (localStorage.getItem('token') != null){ this.authenticated = true; }
    else { this.authenticated = false; }
    console.log(this.authenticated); // for Debugging.
  }



  getUsername(){
    var result = localStorage.getItem('user');
    return result;
  }
}
Run Code Online (Sandbox Code Playgroud)

AJT*_*T82 6

问题是您在组件级别提供服务,这意味着所有将服务添加到providers组件数组中的组件都将拥有自己的服务实例,因此这根本不是共享服务。你想要一个单例服务,所以在你的providers数组中设置服务ngModule.

也像其他人提到的那样,在模板中调用方法是一个非常糟糕的主意,在每次更改检测时都会调用此方法,这经常发生,因此它确实会损害应用程序的性能。

您可以像建议的那样使用 Observables,或者在您的服务中使用共享变量。从长远来看,我建议使用 Observables,但视情况而定,只需要一个共享变量就可以了。这是两者的示例:将数据传递到“路由器出口”子组件(角度 2)


小智 5

一个好的方法是通过与Observable的反应式编码共享数据。

在您的服务中,创建一个BehaviorSubject及其Observable:

private _isAuthenticatedSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public isAuthenticatedObs: Observable<boolean> = _isAuthenticatedSubject.asObservable();
Run Code Online (Sandbox Code Playgroud)

每次您想要更新您的价值时,请next针对您的主题进行:

_isAuthenticatedSubject.next(true); // authenticated
_isAuthenticatedSubject.next(false); // no more
Run Code Online (Sandbox Code Playgroud)

组件方面,只需订阅可观察对象即可为每个主题更改在本地设置值:

this.authService.isAuthenticatedObs.subscribe(isAuth => this.isAuth = isAuth);
Run Code Online (Sandbox Code Playgroud)

或使用异步管道在模板中显示值:

<ng-template *ngIf = "authService.isAuthenticatedObs | async">
Run Code Online (Sandbox Code Playgroud)