簡體   English   中英

Angular2中的* ngIf服務不能很好地工作

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM