2017-10-31 1 views
1

最近、問題が発生しましたが、この時点で私のコードに何が間違っているか分かりません。Angular App内のBehaviorSubjectの動作が混乱しています

私がしようとしているのは、機能付きで私のBehaviorSubjectの値を変更することですが、機能していません。

chat.service.ts

import { Injectable } from '@angular/core'; 
import { BehaviorSubject } from 'rxjs/BehaviorSubject'; 

@Injectable() 
export class ChatService { 
    chatId = new BehaviorSubject<number>(0); 

    constructor() { 
    this.chatId.next(1); 
    } 

    changeChatId(chatId: number) { 
    console.log(chatId); 
    this.chatId.next(chatId); 
    } 
} 

だから、加入者は、デフォルトと同様に、コンストラクタから変更chatIdを取得します。しかし、私がchangeChatId関数で変更しようとすると、何も起こりません。正しいIDが関数に渡されて、既にデバッグされていますが、this.chatId.next(chatId)は何もしていないようです。

これらは、サービスが現在使用されている他の成分である。

チャットメッセージリスト

import { Component, OnInit, Input} from '@angular/core'; 
import { ChatService } from "../../../shared/services/chat.service"; 

@Component({ 
    selector: 'app-chat-message-list', 
    templateUrl: './chat-message-list.component.html', 
    styleUrls: ['./chat-message-list.component.css'], 
    providers: [ChatService] 
}) 
export class ChatMessageListComponent implements OnInit { 
    chatId: number; 

    constructor(private chat: ChatService) { } 

    ngOnInit() { 
    this.chat.chatId.subscribe(
     chatId => this.updateMessageList(chatId) 
    ); 
    } 

} 

チャット項目

import { Component, OnInit, Input} from '@angular/core'; 
import { User } from '../../../shared/models/user.model'; 
import { ChatService } from '../../../shared/services/chat.service'; 

@Component({ 
    selector: 'app-chat-list-item', 
    templateUrl: './chat-list-item.component.html', 
    styleUrls: ['./chat-list-item.component.css'], 
    providers: [ChatService] 
}) 
export class ChatListItemComponent implements OnInit { 
    @Input() 
    user: User; 

    constructor(private chat: ChatService) { } 

    ngOnInit() { 
    } 

    onChatItemSelected(){ 
    this.chat.changeChatId(this.user.id); 
    } 
} 

を追加

答えて

1

ChatServiceをシングルトン(共有)サービスにする必要があります。それをngModuleのプロバイダに追加します。これにより、ChatServiceを使用するすべてのコンポーネントが同じサービスインスタンスを共有できます。

@NgModule({ 
    providers: [ChatService] 
}) 

そして、コンポーネントプロバイダから削除してください。コンポーネントプロバイダに追加する場合、そのコンポーネントは他のコンポーネントで使用できない独自のChatServiceのインスタンスを取得します。

+1

私はそれを3時間くらい無駄にしました。私はすぐにそれを試してみてください。あなたのために早く答えてくれてありがとう:) –

関連する問題