有2个组件,即标头和登录名。 如果loginU的值返回true,那么我想在标题comp中显示注销按钮。在控制台中,其显示布尔值在标头comp中为未定义。
登录comp.ts:
public isloggedin: boolean;
loginU(e) {
e.preventDefault();
console.log(e);
const username = e.target.elements[0].value;
const password = e.target.elements[1].value;
console.log(username, password);
if (username === 'admin' && password === 'admin') {
console.log(e);
this.isloggedin = true;
this.router.navigate(['/dashboard']);
return this.isloggedin
} else {
this.loginStatus = 'Invalid Username/Password';
}
}
header comp:
import {LoginComponent} from '../login/login.component';
constructor private _login: LoginComponent) {
ngOnInit() {
console.log("From header " + this._login.isloggedin)
}
header.component.html:
<button *ngIf="_login.isloggedin" mat-button (click)="logout()" style="outline:none;margin-left: 5px;float: right;">
</button>
答案 0 :(得分:1)
使用BehaviorSubject进行
假装我们有这样的main-container.html
:
<div class="container">
<header-component></header-component>
<login-component></login-component>
</div>
login.service.ts
export class LoginService{
private isLogged$ = new BehaviorSubject<boolean>(null);
public isLoggedEvent = this.isLogged$.asObservable();
public setUserLogged(status: boolean){
this.isLogged$.next(status);
}
}
login.component.ts
//your other stuff
constructor(
private service: LoginService
) { }
loginU(e) {
e.preventDefault();
console.log(e);
const username = e.target.elements[0].value;
const password = e.target.elements[1].value;
console.log(username, password);
if (username === 'admin' && password === 'admin') {
console.log(e);
this.service.setUserLogged(true);
this.router.navigate(['/dashboard']);
return this.isloggedin
} else {
this.loginStatus = 'Invalid Username/Password';
}
}
header.component.ts
export class HeaderComponent implements OnInit{
public isLogged = false;
constructor(
private service: LoginService
) { }
ngOnInit: void {
this.service.isLoggedEvent
.subscribe( isLogged => {
this.isLogged = isLogged;
});
}
logout(){
//your logout stuff
this.service.setUserLogged(false);
}
}
header.component.html
<button *ngIf="isLogged" mat-button (click)="logout()" style="outline:none;margin-left: 5px;float: right;">
</button>
<div *ngIf="!isLogged">User is not logged in</div>
通过这种方式,只要isLogged$
的状态发生变化,您的标头组件就会更新itSelf。如果您想在@Input
上使用login.component
,请告诉我,我将编辑此答案,向您展示如何操作。
答案 1 :(得分:0)
根据组件之间的关系(父/子/兄弟),可以使用以下一种方法来共享boolean
值:
https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/