我有一個服務,我聲明我的變量。 在我的組件中,我使用這個變量來將數據放入它。組件之間的角度 - 共享服務不起作用
服務:
@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