Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
959 views
in Technique[技术] by (71.8m points)

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

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Source: https://angular.io/guide/dependency-injection#injector-hierarchy-and-service-instances

Angular 9 Update

Global level services are now defined as

@Injectable({
  providedIn: 'root',
})
export class DataService {

This should be the recommended approach since it will tree-shake itself if it's unused.

Source: https://angular.io/guide/providers#providedin-and-ngmodules


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...