Angular 如何使用服务在两个不相关的组件之间更新和共享数据
我有一个日历视图,在选择日期时,我将从中获得“日历ID”,并将重定向到主页。我必须将日历ID传递到主页 我已使用服务更新并获取日历ID 事件日历.component.tsAngular 如何使用服务在两个不相关的组件之间更新和共享数据,angular,typescript,angular7,data-sharing,Angular,Typescript,Angular7,Data Sharing,我有一个日历视图,在选择日期时,我将从中获得“日历ID”,并将重定向到主页。我必须将日历ID传递到主页 我已使用服务更新并获取日历ID 事件日历.component.ts selectChange(event,content){ this.selectedvalue= event.target.value; this.http.get(this.calendarUrl+this.formattedDay).subscribe((res)=>{ this.cal
selectChange(event,content){
this.selectedvalue= event.target.value;
this.http.get(this.calendarUrl+this.formattedDay).subscribe((res)=>{
this.calendarID=res;
this._dataservice.setSelectedCalendarId(this.calendarID);
},
(err)=>{
this.calendarID=err
});
if(this.selectedvalue == '1'){
this.router.navigate([''], { queryParams: { load: 'true' } });
this.modal.dismissAll(content);
}
else if(this.selectedvalue == '2'){
this.router.navigate([''],{ queryParams: { load: 'stop' } });
this.modal.dismissAll(content);
}
}
Dataservice.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable()
export class DataserviceService {
public calendarId = new Subject<any>();
selectedCalendarId = this.calendarId.asObservable();
constructor() {
}
setSelectedCalendarId(id){ // set mailid using subject
this.calendarId.next(id); alert(id);
}
}
我得到的数据为“未定义”
请帮助我实现这一点。您需要将服务设置为单例,否则每次组件尝试访问它时,都会创建新的服务距离。在服务中,只需更改以下内容:
@Injectable()
在这方面:
@Injectable({
providedIn: 'root',
})
文档:
@Injectable({
providedIn: 'root',
})