BD's
BD's

Reputation: 33

SPFX with Angular - Not able to use service in component ts file

I have created a project using SharePoint SPFX framework and added necessary packages required for Angular (6.0 or 7.0) typescript. It seems Angular is working in my spfx webpart but when I am trying to create a service using Angular, I am not able to use the methods available in the service from component.ts file. Though no errors are being shown in the project, the method declared in the service is coming as undefined when I am trying to use in the component.ts file

app.service.ts


import { Component, OnInit } from '@angular/core';  
import { Injectable } from '@angular/core';
export interface IDataService {
    getTitle(webUrl:string):string;
}
@Injectable()
export class SharePointService {
     constructor() {}     
     public getTitle(webUrl:string):string {
       return webUrl;
     }
  }  

app.component.ts


import { Component, OnInit } from '@angular/core';  
import {IWebPartContext} from '@microsoft/sp-webpart-base'; 
import { IDataService } from './app.service';

@Component({  
  selector: 'my-spfx-app',  
  template: `<h3>Welcome to SPFx {{name}}!!</h3><p>{{serviceProp}}</p>`
})  
export class AppComponent implements OnInit  {  
    public name: string = '';  
    public context:IWebPartContext;
    public serviceProp:string = "";
    constructor(private dataService: IDataService){  
    }  

   public  ngOnInit() {
        this.context= window["webPartContext"];  
        this.name= this.context.pageContext.user.displayName;        
        this.serviceProp = this.dataService.getTitle("Angular Service Testing");
    }  
}  

Output


Welcome to SPFx User1

Data is not coming to serviceProp variable. Please help us

Upvotes: 0

Views: 251

Answers (1)

Ezzabuzaid
Ezzabuzaid

Reputation: 568

You need to mark the class as the type instead of the interface

private dataService: SharePointService

and don't forget to provide the service either in the root module or in the feature module that contains the component

`@Injectable({ provideIn: 'root' })`

Upvotes: 1

Related Questions