Reputation: 11445
I want to access facebook service inside other component.
This is how I init facebook service in app.component.ts
import { FacebookService } from 'ngx-facebook';
export class AppComponent implements OnInit, OnDestroy, AfterViewInit {
constructor(
@Inject(PLATFORM_ID) private platformId,
private facebookService: FacebookService,
) {}
ngOnInit() {
this.facebookService.init(initParams);
}
}
Now I want to access the this.facebookService
from another component
So I can do something like this
in component hello.ts
dosomething(){
this.facebookService.CustomerChat.showDialog()
}
I got error can not read property showDialog() of undefined.
Upvotes: 0
Views: 147
Reputation: 89
Since Angular services are basically Singletons (i.e: there is only a single instance of the service wherever you are in the application), you can access them from any component by simply injecting them within the component's constructor.
Upvotes: 0
Reputation: 8292
Seems that you are new to Angular. Normally you access the services by injecting them in components constructor.
import { FacebookService } from 'ngx-facebook';
export class MyComponent {
constructor(private fb: FacebookService) {}
callSomeFbMethod() {
this.fb.someMethod();
}
}
You also have to make sure that the service you are injecting is also injected to providers
in your app.module.ts
or which ever module your component depends on. If you are using 3rd party libraries such as this one - ngx-facebook, you will probably have to import the library module and not the service.
import { FacebookModule } from 'ngx-facebook';
@NgModule({
...
imports: [
FacebookModule.forRoot()
],
...
})
export class AppModule { }
If you create your own service, you import it like this:
import { MyService } from 'services/my-service';
@NgModule({
...
providers: [
MyService
],
...
})
export class AppModule { }
Upvotes: 0
Reputation:
## create a shared service.
import { Injectable } from '@angular/core';
import { FacebookService } from 'ngx-facebook';
@Injectable({
providedIn: 'root'
})
export class SharedService {
public get faceBookService() {
return this._facebookService;
}
constructor(private _facebookService: FacebookService) {
}
public initFacebook(initParams: any) {
this._facebookService.init(initParams);
}
}
import { SharedService } from './services/shared.service.ts';
export class AppComponent implements OnInit, OnDestroy, AfterViewInit {
constructor(
@Inject(PLATFORM_ID) private platformId,
private _sharedService: SharedService,
) {}
ngOnInit() {
this._sharedService.facebookService.init(initParams);
}
}
Upvotes: 1