首页 > 解决方案 > 基本的 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;
  }

}

标签: javascriptangulartypescript

解决方案


您应该改为使用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)

推荐阅读