我有一个服务,我声明我的变量。 在我的组件中,我使用这个变量来将数据放入它。组件之间的角度 - 共享服务不起作用
服务:
@Injectable()
export class DataService {
public msgs = [];
constructor() { }
}
现在我用这个变量在我的组件:
export class MessagesComponent implements OnInit {
constructor(private dataService: DataService){}
ngOnInit() {
this.getData();
}
getData(){
let msgs = [];
if (diffr <= this.geomessage[i].range) {
this.geomessage[i].dist = diffr;
msgs.push(this.geomessage[i]);
//console.log("this message: ", this.geomessage[i]); //DEBUG
}
this.dataService.msgs = msgs;
}
}
我只贴了必要的code.The this.dataService.msgs
HET充满信息能正常工作。当我到另一个组件时,this.dataService.msgs的数据仍然存在,但是当我回到Messagescomponent
this.dataService.msgs
是undefined
直到我再次填充它,但我需要其中的数据。有人知道如何做到这一点?
THX
没有添加在NgModule我会尝试 – user3356007
@ user3356007也从'@ Component'注释中移除它 – echonax
如何在组件中使用它如果我不把它放在组件的提供程序构造函数中? – user3356007