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 >
<div >
<p *ngFor="let holder of holders">{{ holder.policyNumber }}</p>
</div>
</div>
CodePudding user response:
Your function getPolicyHolders
only returns something if the condition is respected.
Also return when it is not.
return this.http.get<Policy[]>(...)
CodePudding user response:
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;
})
);
}