首页 > 解决方案 > Angular 中的本地服务不接受数据而不是字符串格式

问题描述

我有这个本地服务:

@Injectable()
export class LocalService {

  private messageSource = new BehaviorSubject(null);
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: any) {
    this.messageSource.next(message)
  }

}

然后,当我在组件中调用它的方法时,就像这样

submitReview(){

  let credentials = {
  author: this.userName,
  review: this.userReview.value,
  movie: this.id
}
this.localService.changeMessage(credentials)
}

我收到此错误Argument of type '{ author: string; review: any; movie: string; }' is not assignable to parameter of type 'string'. ,我不明白,因为消息类型设置为任何...我做错了什么?

标签: angularservicearguments

解决方案


目前尚不清楚,但可能 localService 与您应用程序中的某个地方的 localStorage 交互。localStorage 通过类型字符串获取/设置。在您的有效负载上尝试字符串化:

this.localService.changeMessage(JSON.stringify(credentials))

或者在执行下一步之前在 localService stringify 中:

this.messageSource.next(JSON.stringify(message))

或者最终找到 localStorage 在您的应用程序中实际交互的位置并在那里对其进行字符串化。也许它不是 localStorage,但它可能是类似的东西,需要一个字符串有效负载。无论哪种方式,都可以尝试对有效负载进行字符串化。


推荐阅读