[英]How to fix Angular Service Response to Component - Undefined
I am trying to read a value from API response and use this value from service class, and referring this service variable to all other components, since it is a global value comes from database.我正在尝试从 API 响应中读取一个值并使用来自服务 class 的这个值,并将这个服务变量引用到所有其他组件,因为它是一个来自数据库的全局值。
My Component code below,我的组件代码如下,
export class MyComponent implements OnInit {
constructor(private dateService: DataService) {
}
ngOnInit(): void {
const date = this.dateService.getRunningDay().toDate(); // Here its null
}
}
My Service Class as follows,我的服务Class如下,
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private dateService: DateApiControllerService) {
}
getRunningDay(): Moment {
this.dateService.handleGetExecutionDay().subscribe(data => {
return data;
});
}
While debugging, before getRunningDay method subscribe comes with data, my component date value executed with null.调试时,在 getRunningDay 方法订阅来数据之前,我的组件日期值以 null 执行。
How to fix this issue?如何解决这个问题?
Found a solution for this, I am missing BehaviorSubject's magic.为此找到了解决方案,我缺少 BehaviorSubject 的魔力。 Just wanted to share to someone if get the same issue in future.如果将来遇到同样的问题,只是想与某人分享。
My updated component with subscribe the variable in service class, which is BehaviorSubject type,我更新的组件订阅了服务 class 中的变量,它是 BehaviorSubject 类型,
export class MyComponent implements OnInit {
private date: Date;
constructor(private dateService: DataService) {
}
async ngOnInit(): Promise<void> {
this.dateService.date$.subscribe((data) => this.date = data.toDate());
this.dayMonthYear = this.getDayName(this.date.getDay()) + ' ' + this.getMonthName(this.date.getMonth()) + ' ' + this.date.getDate() + ', ' + this.date.getFullYear();
}
Updated DateService with BehaviorSubject,使用 BehaviorSubject 更新 DateService,
@Injectable({
providedIn: 'root'
})
export class DataService {
runningDate: BehaviorSubject<Moment>;
private date: BehaviorSubject<Moment> = new BehaviorSubject<Moment>(moment());
date$: Observable<Moment>;
constructor(protected httpClient: HttpClient, private dateService: DateApiControllerService, private spinner: NgxSpinnerService) {
this.getRunningDay();
this.date$ = this.date.asObservable();
}
getRunningDay(): any {
if (this.runningDate?.value) {
return this.runningDate.value;
} else {
this.dateService.handleGetExecutionDay().subscribe(data => {
let value = moment(data, 'YYYY-MM-DD');
this.date.next(value);
return data;
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.