У меня есть служба аутентификации, которая испускает событие. Когда пользователь входит в систему (через LoginComponent), навигационная панель должна обновляться (NavBarComponent). Эти компоненты находятся на одном уровнеУгловой 2 - Событие от службы к компоненту на том же уровне
Сначала я попытался использовать 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, а затем обновить навигационную панель. Как я могу сделать ?
EDIT:
Событие получено в NavBarComponent:
this.subscription = authService.stateChange$.subscribe(
value => {
this.connectionState = value;
})
Но значение не обновляется в шаблоне. Мне нужно изменить маршрут, чтобы иметь правильное значение «connectionState»
Если компоненты находятся на одном уровне и предоставлены в одном из них, вы должны получить сообщение об ошибке на другом, что у поставщика нет поставщика. –
Можете ли вы попытаться воспроизвести в Plunker? Plunker предоставляет шаблон для Angular2 TS. –
THX для вашего ответа. Я не могу воспроизвести в Plunker, я не сталкиваюсь с той же проблемой. Я удалил «поставщиков: [AuthService]» из NavBarComponent и есть улучшение: значение «connectionState» изменено, но мне нужно изменить маршрут, чтобы увидеть его модификацию – isy