我是Angular的临时用户,所以也许我缺少明显的东西。
[我跟随了fireship.io的this lesson,使用angularfire将身份验证集成到我的角度应用程序中。
登录后,可观察的AuthService.user $更改,但是该模板未在UserProfile组件中更新。
使用下面的代码片段确认数据在那里。
<pre>{{auth.user$ | async | json}}</pre>
这似乎与在ngzone外部进行更新的可观察值有关。我尝试通过在组件中注入ChangeDetectorRef并从AuthService.user $的订阅回调中触发detectChange来手动检测更改,但没有成功。
我只能通过将user-profile.component.ts更改为以下内容来使其按预期工作:
@Component({
selector: 'app-user-profile',
templateUrl: './user-profile.component.html',
styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent implements OnInit {
userData?: User;
constructor(public auth: AuthService) {
this.auth.user$.subscribe(d => this.userData = d)
}
}
和user-profile.component.html到以下:
<div *ngIf="userData; then authenticated else guest">
</div>
<ng-template #guest>
<h3>Hello</h3>
<p>Login to get started...</p>
<button (click)="auth.googleLogin()">
<i class="fa fa-google"></i> Connect Google
</button>
</ng-template>
<ng-template #authenticated>
<div *ngIf="userData as user">
<h3>Hello, {{ user.displayName }}</h3>
<img [src]="user.photoURL">
<button (click)="auth.signOut()">Logout</button>
</div>
</ng-template>
这里是我的依赖项,从package.json中提取。
{
"@angular/animations": "~8.2.14",
"@angular/common": "~8.2.14",
"@angular/compiler": "~8.2.14",
"@angular/core": "~8.2.14",
"@angular/fire": "^5.4.0",
"@angular/forms": "~8.2.14",
"@angular/platform-browser": "~8.2.14",
"@angular/platform-browser-dynamic": "~8.2.14",
"@angular/router": "~8.2.14",
"firebase": "^7.8.0",
"rxjs": "~6.4.0",
"tslib": "^1.10.0",
"zone.js": "~0.9.1"
}
我可能会想念的任何想法吗?
除非我没有记错,否则您只需要更改Jeff Delaney's example的代码。
您正在ng-template
上使用两个async
以及两个AuthService.user$
订阅,(一个在div
容器中,另一个在ng-template
容器中称为authenticated
。这是导致您的问题。
使用下面的代码,它将运行顺利:
<div *ngIf="auth.user$ | async as user; else guest">
<h3>Hello, {{ user.displayName }}</h3>
<img [src]="user.photoURL">
<button (click)="auth.signOut()">Logout</button>
</div>
<ng-template #guest>
...
</ng-template>
如果要保留初始代码,可以考虑将shareReplay
运算符添加到可观察的AuthService.user$
中。在这种情况下,Observable
的最后一个值将始终可用于新订阅。
this.user$ = this.afAuth.authState.pipe(
switchMap(user => {
if (user) {
return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
} else {
return of(null);
}
}),
shareReplay(1)
);