Angular 2 Setter and Getter

17,771

Solution 1

If you want to share a service across components that are not children of the parent component, you need to register the service in the module, not in the component. When you register a service within a component, it is only available to that component and its children.

Something like this:

@NgModule({
  declarations: [
    AppComponent,
    ProductListComponent,
    StarComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [ TestService ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Solution 2

If you are trying to interact between two components which are from different modules, then you have to import your service into the app module(i.e main module), in this way get method does not return

Share:
17,771
Tony Hensler
Author by

Tony Hensler

Fixing the world, 1 line of code at a time.

Updated on June 13, 2022

Comments

  • Tony Hensler
    Tony Hensler almost 2 years

    I am attempting to create a service to parse data to different components on different routes.

    If I call the follow service on the same component I get the result I require, but if I try to get the set results from another component the service returns undefined.

    Here is my service:-

    import {Injectable} from '@angular/core';
    
    @Injectable()
    export class TestService {
    
      public _test:any;
    
      set test(value:any) {
        this._test = value
      }
    
      get test():any {
        return this._test;
      }
    }
    

    I set the service like:-

    this.testService.test = 3;
    

    and I receive the the service data in my component using the following:-

    console.log(this.testService.test)
    

    As mention before this works absolutely fine if I am communicating within the same component, I have the same imports, providers and constructor.

    Also just a note the components are sibling components

    Would anybody be able to help or point me in the right direction it would be very appreciated.

    If you require any extra code please let me know.