I recently developed a project using the SharePoint SPFX framework and integrated all the necessary Angular (6.0 or 7.0) TypeScript packages. While Angular seems to be functioning properly within my SPFx webpart, I encountered an issue when attempting to create a service with Angular. Despite not receiving any errors in the project, the method defined in the service appears as undefined when I try to access it from 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){
}
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 being retrieved for the serviceProp
variable. Any assistance would be greatly appreciated.