javascript - 基本的 Angular CRUD 服务?
问题描述
我在设置 CRUD 服务时遇到问题,我可以调用该服务来设置和获取 2 个组件之间的特定值...
字符串不可分配给主题类型
export class ChangeService {
colour: Subject<string>;
constructor() {
this.colour = new Subject();
}
changeColour(colour: string) {
// this is where the TS error is thrown
this.colour = colour;
}
getColour(): Observable<any> {
return this.colour;
}
}
解决方案
您应该改为使用BehaviorSubject
并调用该next
方法。
export class ChangeService {
colour: BehaviorSubject<string> = new BehaviorSubject<string>(null);
changeColour(colour: string) {
this.colour.next(colour);
}
}
要获得颜色,您只需colour
在组件类中订阅即可。
color;
constructor(private changeService: ChangeService) {}
this.changeService.colour.subscribe(color => this.color = color)
推荐阅读
- unit-testing - 如何更改模块中的 Perl Readonly 标量以进行单元测试?
- mysql - 我需要 information_schema、mysql、performance_Schema、phpmyadmin 数据库吗?
- reactjs - Mongoose 更新功能替换而不是推送 React 应用程序中的其他条目
- r - 在通过 ODBC 连接到数据库的 R 中,如何在运行一个查询后断开连接以发送另一个查询而不取消前一个查询?
- android - Android Studio 4.1 版中不再有 Styles.xml
- javascript - 为什么我定义
- go - 从 golang linter 中排除生成的结构
- powershell - NSSM Powershell 脚本 Windows 2012 服务器。创建服务时出错
- bash - 通过 shell 输出表格格式
- xamarin - 绑定值更改时如何触发函数?