Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot read properties of undefined (reading 'subscribe') in Angular

just trying to figure something out.

So I created service and a component in angular however I’m getting an error – Cannot read properties of undefined (reading ‘subscribe’)

Was wondering where i am going wrong.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please see the below code:

Service

import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { of } from "rxjs";
import { map } from "rxjs/operators";
import { environment } from "src/environments/environment";
import { Policy } from "../models/Policy";

@Injectable({
  providedIn: "root",
})
export class PolicyholdersService {
  baseUrl = environment.apiUrl;
  policy: Policy[] = [];

  constructor(private http: HttpClient) {}

  getPolicyHolders() {
    if (this.policy.length > 0) {
      return of(this.policy);
    }
    this.http.get<Policy[]>(this.baseUrl + "policy").pipe(
      map((policy) => {
        this.policy = policy;
        return policy;
      })
    );
  }
}

Component

import { Component, OnInit } from "@angular/core";
import { Policy } from "src/app/models/Policy";
import { PolicyholdersService } from "src/app/_services/policyholders.service";

@Component({
  selector: "app-policy-holder-list",
  templateUrl: "./policy-holder-list.component.html",
  styleUrls: ["./policy-holder-list.component.css"],
})
export class PolicyHolderListComponent implements OnInit {
  holders: Policy[];

  constructor(private policyservice: PolicyholdersService) {}

  ngOnInit() {
    this.loadPolicyHolder();
  }

  loadPolicyHolder() {
    this.policyservice.getPolicyHolders().subscribe((holders) => {
      this.holders = holders;
    });
  }
}

HTML

<div class="row">
  <div class="col-2">
    <p *ngFor="let holder of holders">{{ holder.policyNumber }}</p>
  </div>
</div>

>Solution :

Your function getPolicyHolders only returns something if the condition is respected.

Also return when it is not.


return this.http.get<Policy[]>(...)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading