Javascript 在我的Angular应用程序中混淆行为主体的行为
我最近遇到了一个问题,现在还不能确定我的代码到底出了什么问题,希望你们中的一些人能帮助我 我所要做的就是用一个函数更改我的Javascript 在我的Angular应用程序中混淆行为主体的行为,javascript,angular,observable,Javascript,Angular,Observable,我最近遇到了一个问题,现在还不能确定我的代码到底出了什么问题,希望你们中的一些人能帮助我 我所要做的就是用一个函数更改我的BehaviorSubject的值,但它不起作用 chat.service.ts import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; @Injectable() export class ChatService { chat
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);
}
}
聊天项目
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);
}
}
您需要使您的聊天室服务成为单例(共享)服务。将其添加到ngModule的提供程序中。这允许使用ChatService的所有组件共享同一个服务实例
@NgModule({
providers: [ChatService]
})
并将其从组件提供程序中删除。当您将其添加到组件提供商时,该组件将获得其自己的ChatService实例,其他组件无法使用该实例。我在这方面浪费了大约3个小时,即使我们有大约1.20个上午,我也会立即尝试。非常感谢您的快速回答:)
@NgModule({
providers: [ChatService]
})