Angular-组件之间的共享服务不起作用 [英] Angular - shared service between components doesn't work
问题描述
我有一个声明变量的服务. 在我的组件中,我使用此变量将数据放入其中.
I have a service where I declare my variable. In my component I use this variable to put data into it.
服务:
@Injectable()
export class DataService {
public msgs = [];
constructor() { }
}
现在我在组件中使用此变量:
Now I use this variable in my component:
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;
}
}
我只张贴了必要的代码.this.dataService.msgs
充满了消息,效果很好.当我转到另一个组件时,this.dataService.msgs的数据仍然存在,但是当我回到Messagescomponent
时,this.dataService.msgs
是undefined
,直到我再次填充它,但我需要其中的数据.有人知道该怎么做吗?
I have only posted the necessary code.The this.dataService.msgs
het filled with messages this works fine. When I got to another component the data of this.dataService.msgs still exists but when i Get back tot the Messagescomponent
the this.dataService.msgs
is undefined
till i fill it again but I need the data that was in it. Does somebody know how to do this?
Thx
推荐答案
如果要在@Component
批注的providers数组内提供DataService
,则
If you are providing your DataService
inside the providers array of your @Component
annotation,
@Component({
...
providers: [DataService],
})...
此服务将是此组件的单例(它将创建一个新实例)(如果未在其批注下也提供此服务,则为子项).
this service will be a singleton (it will create a new instance) for this component (and it's children if they have not provided this service under their annotation also).
如果要在多个组件之间使用此服务并共享该服务的同一实例;您需要在组件/模块中提供此服务,该组件/模块是DI树中这些组件的父级.如果这是一项全局服务,建议您在AppModule(或共享模块)中仅提供它.
If you want to use this service among multiple components and share the same instance of the service; you need to provide this service in a component/module which is the parent of these components in the DI tree. If this is a global service I suggest providing it only in your AppModule (or in a shared module).
@NgModule({
providers:[DataService]
})
来源: https://angular.io/guide/dependency-injection#injector层次结构和服务实例
这篇关于Angular-组件之间的共享服务不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!