【发布时间】:2017-07-08 19:27:12
【问题描述】:
我有一个发出事件的身份验证服务。当用户登录时(通过 LoginComponent),导航栏必须更新(NavBarComponent)。这些组件处于同一级别
首先我尝试使用 EventEmitter,然后我了解到我们不应该在服务中使用它。那是一种反模式。
所以我尝试了https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
auth.service.ts
import {Injectable} from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class AuthService {
private connectionState: boolean;
private stateChangeSource = new Subject<boolean>();
// Observable boolean stream
stateChange$ = this.stateChangeSource.asObservable();
constructor(private http: Http) {
}
changeConnectionState() {
this.stateChangeSource.next(!this.connectionState);
}
}
login.component.ts
import {Component, Inject} from '@angular/core';
import {AuthService} from './auth.service';
@Component({
selector: 'login-component',
templateUrl: './login.component.html'
})
export class LoginComponent {
constructor(private authService: AuthService) {
this.authService = authService;
}
login () {
this.authService.changeConnectionState();
}
}
navbar.component.ts
import {Component} from '@angular/core';
import {AuthService} from './auth.service';
@Component({
selector: 'navbar',
templateUrl: './navbar.component.html',
providers: [AuthService]
})
export class NavbarComponent {
authService: AuthService;
connectionState: boolean;
subscription: any;
constructor(private authService: AuthService) {
this.authService = authService;
this.subscription = authService.stateChange$.subscribe(
value => {
this.connectionState = value;
})
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
navbar.component.html
<nav class="navbar navbar-default navbar-fixed-top">
...
<a *ngIf="!connectionState" [routerLink]="['/login']">Connect</a>
<a *ngIf="connectionState" (click)="disconnect()">Disconnect</a>
...
</nav>
当我打电话时
this.authService.changeConnectionState();
来自 NavbarComponent,导航栏已正确更新。 但我想从 loginComponent 更改连接状态,然后更新导航栏。我该怎么办?
编辑:
在 NavBarComponent 中接收到事件:
this.subscription = authService.stateChange$.subscribe(
value => {
this.connectionState = value;
})
但是模板中的值没有更新。我必须更改路线才能获得正确的“connectionState”值
【问题讨论】:
-
如果组件处于同一级别并在其中一个提供,您应该在另一个上收到错误消息,即没有该服务的提供者。
-
你能尝试在 Plunker 中复制吗? Plunker 提供了 Angular2 TS 的模板。
-
感谢您的回答。我无法在 Plunker 中重现,我没有遇到同样的问题。我从 NavBarComponent 中删除了“providers:[AuthService]”,并且有一个改进:“connectionState”值已更改,但我必须更改路线才能看到其修改
标签: angular events login angular-services angular-components