我在角度5中使用* IF-else语句。如果授权值为true,则模板2应该渲染,如果不是模板1应该渲染。这是代码
<div *ngIf="authorized; then picUrl else login"></div>
<ng-template #login>
<button mat-raised-button color="accent" class="mdl-cell mdl-cell--12-col mdl-color-text--white" style="background: #033342" (click)="openDialog()">Login</button>
</ng-template>
<ng-template #picUrl>
<img src="{{_loginVM.profilePic}}" class="img-thumbnail" alt="profile pic">
</ng-template>
调用社交组件
<social></social>
App.component.ts
export class AppComponent {
public authorized: boolean = false;
}
社交组件
import { AppComponent} from '../app/app.component'
export class SocialComponent {
private _appComponent: AppComponent;
constructor(private socialAuthService: AuthService, appComponent: AppComponent,
public dialogRef: MatDialogRef<SignInSignUpDialogHomeComponent>) {
this._appComponent = appComponent;
}
public socialSignIn(socialPlatform: string) {
let socialPlatformProvider: any;
if (socialPlatform == "facebook") {
socialPlatformProvider = FacebookLoginProvider.PROVIDER_ID;
} else if (socialPlatform == "google") {
socialPlatformProvider = GoogleLoginProvider.PROVIDER_ID;
}
this.socialAuthService.signIn(socialPlatformProvider).then(
(userData) => {
if (userData != null) {
this._appComponent.authorized = true;
this._appComponent._loginVM.profilePic = userData.image;
this.dialogRef.close();
}
}
);
}
成功登录后,该值将更新为this._appComponent.authorized = true;
。该值不会反映到UI / UX。
我从这里找到了一些参考资料 https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/
我试过BehaviorSubject<boolean>
。但不知道如何订阅UI数据绑定。是的,这是我必须做的事情吗?我不能直接对组件变量做什么?
答案 0 :(得分:1)
.html
<div *ngIf="authorized; then picUrl else login"></div>
component.ts
ngOnInit() {
this.authorized= this.authService.isLoggedIn;
}
service.ts
get isLoggedIn(): boolean {
return this.currentUser != null; //you can decide to return true or false
}
get currentuser(): user{
let user = localstorage.getitem('details')
return user;
}