'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.
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 1:[1]
Your function getPolicyHolders only returns something if the condition is respected.
Also return when it is not.
return this.http.get<Policy[]>(...)
Solution 2:[2]
You missed the return statement in your service.
getPolicyHolders() {
if (this.policy.length > 0) {
return of(this.policy);
}
// return the value
return this.http.get<Policy[]>(this.baseUrl + "policy").pipe(
map((policy) => {
this.policy = policy;
return policy;
})
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | temp_user |
| Solution 2 | Justwell Solets |
