早上好,我正在开发一个简单的应用程序,用来训练自己,但我似乎无法捕捉到服务中的变化。我的意思是,我有一个组件从服务中订阅一个变量,但是当服务中的变量被更新时,组件中的变量就没有了。
我的组成部分:
import { AfterViewInit, Component, OnDestroy } from '@angular/core';
import { AnswersService } from "./answers.service";
export class AnswersComponent implements AfterViewInit, OnDestroy {
hours = [];
constructor(private answersService: AnswersService) {
this.answersService.hours.subscribe(value => {
this.hours = value; // value doesn't get changed
console.log(value); // never gets logged
});
}
// ... then i use the this.hours variable down below
}我的服务:
import { Injectable, OnInit } from '@angular/core';
import { ServerService } from '../../../server.service';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class AnswersService implements OnInit {
constructor(private server: ServerService) { }
hours = new Subject<any[]>();
ngOnInit() {
this.getHours(); // on init i get the new data
}
private getHours() { // when this happens, my Subject should be updated
this.hours.next(['03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', '00:00', '01:00', '02:00']);
}
}我的组件中的预期行为是,小时最初是一个空数组,但是在满足数据库请求之后,它应该成为您在服务中看到的长字符串数组。
我有什么不正确的理解?很多向导/StackOverflow回答我尝试过的问题,所以我不明白问题出在哪里。
编辑:和建议的一样,我将更新的方法调用从onInit (服务不能正常工作)转移到构造函数。另外,我把它从Subject改为BehaviorSubject。
现在的问题是,如果我想分配从数据库获取的数据,它就不再更新了。
private getHours() {
this.server.getExperiment({id:1}).then((response: any) => {
// Just a simple endpoint I've set for this time
this.hours.next(['03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', '00:00', '01:00', '02:00']);
});
}getExperiment的实现方式是:
private async request(method: string, url: string, data?: any) {
const result = this.http.request(method, url, {
body: data,
responseType: 'json',
observe: 'body'
});
return new Promise((resolve, reject) => {
result.subscribe(resolve, reject);
});
}
getExperiment(experiment) {
return this.request('GET', `http://localhost:8080/experiment/${experiment.id}`);
}在注释之后,我尝试编辑它(产生相同的结果)如下:
private request(method: string, url: string, data?: any) {
return this.http.request(method, url, {
body: data,
responseType: 'json',
observe: 'body'
});
}这样我就可以订阅而不是等待承诺:
private getHours() {
this.server.getExperiment({id:1}).subscribe((response: any) => {
this.hours.next(['03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', '00:00', '01:00', '02:00']);
});
}发布于 2019-10-29 12:31:57
对于可能有同样问题的每一个人:在评论中采取的解决办法解决了这个问题。我的第二个问题是异步问题,我在组件中没有正确使用订阅服务器。
感谢所有帮助我发表评论的人。
https://stackoverflow.com/questions/58605776
复制相似问题