gpt4 book ai didi

angular - 模型更改时 View 未更新

转载 作者:太空狗 更新时间:2023-10-29 17:58:40 25 4
gpt4 key购买 nike

我有一个 Angular (5.2.3) 应用程序,我想在其中的页面右上角显示一个登录/注销按钮。在幕后,我尝试使用外部 Open ID Connect 提供商静默登录用户。当回调到达时,我想显示用户名和注销按钮。但遗憾的是, View 永远不会更新以反射(reflect)这一点。

这是组件的 View :

<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 调用都按预期执行,只有 View 永远不会更新。

最佳答案

你的问题和另一个问题类似,我把答案放过去了。

Trigger update of component view from service - No Provider for ChangeDetectorRef

您需要做的是强制 Angular 更新您的 View 。您可以使用 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).

关于angular - 模型更改时 View 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48579167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com