javascript - Angular 4 Singleton Services -
i'm trying create service share data between 2 components. injected service root module make accessible throughout application doing di root module provider. code looks this.
service
@injectable(){ export class forumservice{ forum: any; setforum(object){ this.forum = object; } getforum(){ return this.forum; } }
root module
....... import { forumservice } 'forumservice'; ....... @ngmodule({ declarations: [.....], imports: [.....], providers: [....., forumservice], bootstrap: [appcomponent] }) export class appmodule{}
component one
//a bunch of import statements import { forumservice } 'forumservice'; //without angular throws compilation error @component({ selector: 'app-general-discussion', templateurl: './general-discussion.component.html', styleurls: ['./general-discussion.component.css'], providers: [generaldiscussionservice] //not injecting forumservice again }) export class generaldiscussioncomponent implements oninit{ constructor(private forumservice: forumservice){} ngoninit(){ helperfunction(); } helperfunction(){ //get data backend , set forumservice this.forumservice.forum = data; console.log(this.forumservice.forum); //prints data, not undefined } }
component two
//a bunch of import statements import { forumservice } 'forumservice'; //without angular throws compilation error @component({ selector: 'app-forum', templateurl: './forum.component.html', styleurls: ['./forum.component.css'], providers: [] }) export class forumcomponent implements oninit { forumdata: any; constructor(private forumservice: forumservice){} ngoninit(){ this.forumdata = this.forumservice.forum; // returns undefined } }
once navigate component 1 component 2 i'm expecting "this string". undefined
. because of import statements in component? if remove see compilation error saying forumservice
not found.
instead of using getter , setter, use object (not primitibe such string) directly in components.
your service
@injectable(){ export class forumservice{ forum:any = {name:string}; }
component one
export class generaldiscussioncomponent implements oninit{ constructor(private forumservice: forumservice){} ngoninit(){ this.forumservice.forum.name="this string"; } }
component two
export class forumcomponent implements oninit { // forumtitle: string; // not need anymore forum:any; // use forum.name property in html constructor(private forumservice: forumservice){} ngoninit(){ this.forum = this.forumservice.forum; // use } }
i know encapsulating preferable, , current code encountering timing problems. when working shared data in service can two-way bind variable above, , components in sync.
edit:
also important notice, variable want sync between components needs object. instead of forumtitle:string
, make forumtitle:any = {subject:string}
or similar.
otherwise need make components listeners data when data changes in service.
Comments
Post a Comment