Angular: member variable undefined within function

Viewed 218

I have the following service, which has a function that returns an Observable, since it takes data from another service, transforms it and then returns it (as an Observable).

@Injectable({
  providedIn: 'root'
})
export class ReportColumnHeaderService {

  constructor(private companyService: CompanyService) {}

  public getColumnHeaderElements(variableDimensions: string[]): Observable<HeaderElement[]> {

    return Observable.create(function(observer) {

      this.companyService.getCompanies( (companies: Company[]) => {
        let headerElements = getHeaderElements(companies);
        observer.next(headerElements);
        observer.complete();
      });

    });

  }
}

The problem is that this.companyService is undefined within the function. I read that it should possible if I use an => like that:

return Observable.create((observer)  => {

   this.companyService.getCompanies( (companies: Company[]) => {
   let headerElements = let headerElements = getHeaderElements(companies);
   observer.next(headerElements);
   observer.complete();
  });

});

But that code does not compile. It says Expected 0 arguments, but got 1. Can someone give me a hint how to solve the problem?

2 Answers

Assuming that getCompanies returns an observable, you are missing subscribe on the funtion. The correct call is given below:

this.companyService.getCompanies().subscribe( (companies: Company[]) => {
  this.companyService.getCompanies( (companies: Company[]) => {
        let headerElements = getHeaderElements(companies);
        observer.next(headerElements);
        observer.complete();
      });

if you want get data from service, you need to use subscribe. The best aproch would be create your constant in method or public variable. For example

companies: Company[];


this.companyService.getCompanies.subscribe((res) => {
                this.companies = res;
                console.log(this.compmanies)
                /** this is just simple exemple */            
              });

Subscribing to observables Remember, observables are lazy. If you don’t subscribe nothing is going to happen. It’s good to know that when you subscribe to an observer, each call of subscribe() will trigger it’s own independent execution for that given observer. Subscribe calls are not shared among multiple subscribers to the same observable. https://medium.com/@luukgruijs/understanding-creating-and-subscribing-to-observables-in-angular-426dbf0b04a3

And of course if you create subscribe, do not forgot to unsubscribe.

Related