[英]Service does not work well with *ngIf in Angular2
編輯:嗯,我應該更清楚。 這是一個有角度的流星項目。 因為流星是反應性的,所以可能還有其他方法。 但@ lodewijk-bogaards是純Angular2項目的一個很好的解決方案。
我正在使用Angular 2(TypeScript)。
我嘗試使用ChatService
服務將值“12345”從App
傳遞給ChatDetailsComponent
。
如果布爾showChatDetails
為true,則在我第一次單擊Show按鈕時它將顯示“12345”,這樣效果很好。
問題是,如果布爾值showChatDetails
為false,則在第二次單擊“顯示”按鈕后,它將顯示“12345”。 我不知道為什么它第二次點擊它時才有效,這也應該是第一次。
(請不要切換到[隱藏],因為我需要* ngIf。)
// app.ts
import {Component, View} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {ChatService} from './chat.service';
import {ChatDetailsComponent} from './chat-details.component';
@Component({
selector: 'app'
})
@View({
directives: [ChatDetailsComponent],
template: `
<button (click)="showButton()">Show</button>
<chat-details-component *ngIf="showChatDetails"></chat-details-component>
`
})
class App {
// Here if it is true, it works well. If it is false, the problem comes.
showChatDetails:boolean = false;
constructor(private _chatService: ChatService) {}
showButton() {
this._chatService.setChatId("12345");
this.showChatDetails = true;
}
}
bootstrap(App, [ChatService]);
// chat-details.component.ts
import {Component, View} from 'angular2/core';
import {ChatService} from './chat.service';
@Component({
selector: 'chat-details-component'
})
@View({
template: `
<div>ID: {{chatId}}</div>
`
})
export class ChatDetailsComponent {
chatId:string;
constructor(private _chatService: ChatService){}
ngOnInit() {
this._chatService.getChatId().subscribe(id => this.chatId = id);
}
}
// chat.service.ts
import {EventEmitter} from 'angular2/core';
export class ChatService {
chatId: EventEmitter<string> = new EventEmitter();
setChatId(id) {
this.chatId.emit(id);
}
getChatId() {
return this.chatId;
}
}
對我來說看起來像是一場競爭。 如果ChatDetailsComponent
訂閱了ChatService
后 chatId
已經發出它不會接受它。 這很容易實現,因為Angular將在Rx計划事件發射的同時安排組件的創建。
我可以提出多種解決方案,但我建議您考慮使用ReplaySubject而不是EventEmitter。
我不確定你的目標是按照你所陳述的方式完成任務,或者你是否靈活完成任務。
我認為這是更容易出錯,使chatId的@Input()
的ChatDetailsComponent
和具有App
創建組件時的新實例chatId
變化。
包含組件必須知道何時需要創建ChatDetailsComponent
的實例。 讓它通過所需的chatId
irhgt似乎是一個更好的方法對我來說。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.