angular – 模型更改时视图未更新
我有一个Angular(5.2.3)应用程序,我想在页面的右上角显示登录/注销按钮.在幕后,我尝试使用外部Open ID Connect提供程序以静默方式登录用户.当回调到来时,我想显示用户的名字和注销按钮.但唉,这个观点永远不会更新以反映这一点.
这是组件的视图: <ul class="navbar-nav"> <li class="nav-item" *ngIf="!loggedIn"> <a href="#" class="nav-link" (click)="login()">Login</a> </li> <li class="nav-item" *ngIf="loggedIn"> <a href="#" class="nav-link disabled" disabled>Hello,{{ name }}</a> </li> <li class="nav-item" *ngIf="loggedIn"> <a href="#" class="nav-link" (click)="logoff()">Logout</a> </li> </ul> 我已经尝试了各种方法来解决这个问题,基于StackOverflow上的各种问题.这是组件现在的样子: import { Component,OnInit,SimpleChanges,ApplicationRef,ChangeDetectorRef,NgZone } from '@angular/core'; import { OAuthService } from 'angular-oauth2-oidc'; import { SessionService } from '../session.service'; @Component({ selector: 'app-navigation',templateUrl: './navigation.component.html',styleUrls: ['./navigation.component.css'] }) export class NavigationComponent implements OnInit { name: string; loggedIn: boolean; constructor(private oauthService: OAuthService,private sessionService: SessionService,private applicationRef: ApplicationRef,private zone: NgZone,private cd: ChangeDetectorRef) { //this.loggedIn = false; } ngOnInit() { this.sessionService.state.subscribe(isLoggedIn => { console.log('Detected a state change! User is logged in: ' + isLoggedIn); this.zone.run(() => { if (!isLoggedIn) { this.name = null; this.loggedIn = false; console.log('User not logged in. Name is set to null'); } else { const claims: any = this.oauthService.getIdentityClaims(); console.log(`Got claims. Name is now ${claims.name}`); this.name = claims.name; this.loggedIn = true; } }); this.cd.detectChanges(); this.applicationRef.tick(); }); this.sessionService.configureWithNewConfigApi(); } public login() {} public logoff() {} } 所有console.log调用都按预期执行,只有视图永远不会更新. 解决方法
你的问题与另一个问题相似,我过去曾回答过这个问题.
Trigger update of component view from service – No Provider for ChangeDetectorRef 您需要做的是强制Angular更新您的视图.你可以用ApplicationRef做到这一点.这就是您的服务的样子: import {Injectable,ApplicationRef } from '@angular/core'; @Injectable() export class UserService { private isLoggedIn: boolean = false; constructor(private ref: ApplicationRef) {} checkLogin() { let stillLogged = //some logic making API calls,or anything other. if (this.isLoggedIn != stillLogged) { this.isLoggedIn = stillLogged; this.ref.tick(); //trigger Angular to update view. } } } In this documentation page you can find out more about ApplicationRef Live example – here I am using AppRef to trigger view update when client subscribes to push on Safari browser. 您也可以尝试移动this.applicationRef.tick();在this.zone.run(()=> {})内; (如果你真的需要NgZone). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |