【问题标题】:Can't use result from subscribe angular无法使用订阅角度的结果
【发布时间】:2019-06-26 03:55:23
【问题描述】:

我遵循this 指南,并尝试在不相关的组件:与服务共享数据段落中做类似的事情

数据服务:

 @Injectable()
export class MyDataService{

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

  constructor(private http: HttpClient) {
    setInterval(() => { this.changeMessage(this.resultFromRestCall()); }, 10 * 1000);
  }

  changeMessage(message: object) {
    this.messageSource.next(message);
  }

  resultFromRestCall(){
    const json;
    this.http.get<object>(myApiUrl).subscribe(res => 
       json['data'] = res['data'] //this is an example
    );
    return json;
  }

组件:

export class MyComponent implements OnInit {

  constructor(private dataservice: MyDataService) {}

  ngOnInit() {
    this.dataservice.currentMessage.subscribe(
      message => {this.handleVarChange(message); }
    );
  }

  handleVarChange(message) {
    console.log(message.data);
  }
  • 使用此代码,我在 handleVarChange 日志中得到“未定义”

  • 我没有在订阅中调用 this.handleVarChange(message);,而是编写了 console.log(message) 我得到了正确的结果。

  • 所以,我的问题是是否可以在我的组件的某些功能中使用来自数据服务的值。

提前致谢

【问题讨论】:

  • resultFromRestCall 方法是异步的吗?
  • 当您提供 resultFromRestCall(...) 实现时会很有帮助。
  • 您的message 看起来如何,您没有显示...您可以创建minimal reproducible example
  • @Batajus 我已经用resultFromRestCall() 实施更新了我的问题。
  • @AJT_82 我在订阅中为json赋值,我已经更新了代码,我之前错过了。

标签: javascript angular components observer-pattern subscribe


【解决方案1】:

与:

resultFromRestCall(){
  const json;
  this.http.get<object>(myApiUrl).subscribe(res => 
     // takes x amount of time to populate json
     json['data'] = res['data'] //this is an example
  );
 // executed instantly after above request has been called 
 return json;
}

您正在返回json它被填充之前,因为请求是异步的。

相反,您可以稍微翻转一下,然后先调用resultFromRestCall(),当您收到响应时,然后调用changeMessage()

setInterval(() => { 
  this.resultFromRestCall().subscribe((data) => {
    this.changeMessage(data);
  });
}, 10 * 1000);

resultFromRestCall 只返回一个 observable:

resultFromRestCall(){
  return this.http.get<object>(myApiUrl);
}

还记得在OnDestroyclearInterval

DEMO

【讨论】:

  • 太好了,很高兴听到! :)
【解决方案2】:

handleVarChange 中省略.data

代替

handleVarChange(message) {
  console.log(message.data);
}

handleVarChange(message) {
  console.log(message);
}

【讨论】:

  • 数据是我消息中的一个数组,我必须访问它。如果我在订阅中记录消息,则数据数组已正确填充。这不是问题的重点。
猜你喜欢
  • 2021-09-02
  • 2021-01-20
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多