Home > database >  I cannot access to some method from a service in Angular
I cannot access to some method from a service in Angular

Time:07-26

I have created an Angular 12 application. Where I have a service FormService to retrieve information from some forms.

@Injectable({
  providedIn: 'root'
})
export class FormService {
  jsonUrl = './assets/forms/form.json';
  defaultForm = 'form';


  constructor(private http: HttpClient, private logger: LogService) {
  }


  getFormName(): Observable<string> {
    return this.http.get(this.jsonUrl)
      .pipe((res: any) => res.label);
  }
  ...

I only show one simple method to make it simpler. I am injecting this service in the app-component ngOnInit to load some default information.

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit, AfterViewInit {


constructor(
    ...
    private formService: FormService,
    ...
  ) {
  }

 ngOnInit(): void {
  this.formService.getFormName()
    .subscribe(data => {
      this.formName = data;
 });

When I run the application, I get a simple error as:

this.formService.getFormName() is undefined

Then, I am trying to show the content of formService by console:

method not accesble!

According to the structure, seems that the formService is injected, but the methods are not generated yet. In fact, formService is defined, but getFormName not!

Why the methods are not yet accessible?

CodePudding user response:

Check the app.module.ts, are you already import HttpClientModule?

CodePudding user response:

Ok, the http was involved as I have imagined. Currently I am migrating this application from Angular 4 to Angular 12. And I have compared with other http requests in other applications I have created using Angular 12 directly.

If, I change:

  getFormName(): Observable<string> {
    return this.http.get(this.jsonUrl)
      .pipe((res: any) => res.label);
  }

To something like this:

  getFormName(): Observable<string> {
    return this.http.get<string>(this.jsonUrl)
      .pipe(
        tap(_ => this.logger.info('fetched form!')),
        catchError(this.logger.handleError<string>('failure getting form name!'))
      );
  }

Or better, with a Promise:

  getFormName(): Promise<string> {
    return new Promise<string>((resolve, reject) => {
      const form: Observable<Form> = this.http.get<Form>(this.jsonUrl);
      if (form) {
        form.subscribe(content => {
          resolve(content.label);
        });
      } else {
        reject('Form not found!');
      }
    });
  }

It is working fine. When I use a console log I do not get the undefined result any more. I am not an expert in Angular, and sure not in Angular 4. But seems that the pipe defined that was working previously in Angular 4, has a different behavior in Angular 12.

CodePudding user response:

did you add this service in the providers array in app.module

  • Related