Angular - shared service between components doesn't work

时间:2017-05-16 09:26:51

标签: angular variables service components sharedservices

I have a service where I declare my variable. In my component I use this variable to put data into it.

Service:

@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;

    }    
}    

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

2 个答案:

答案 0 :(得分:8)

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).

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]
})

答案 1 :(得分:3)

只是快速阐述echonax的回复,是提供者作为层次结构工作。如果您将其添加到app-module,它将在整个应用程序中运行,因此您不应该在其他任何地方“提供”它。 但是,如果不需要“全局”服务,只需在父组件上提供它。