In my service, I have the functionality to either store an object for access in other components or request data from a web API and return it in a map.
Example of retrieving data from objectService:
get(): any {
if (this.object == undefined || this.object == null) {
return this.http.get(this.baseUrl + "/companies/get)
.map((data: any) => {
this.object = data;
return this.object;
});
} else {
return this.object;
}
}
Using the service to set page title:
ngOnInit() {
this.objectService.get().subscribe((data: any) => {
this.title.setTitle(data.name);
});
}
While this setup works initially when loading the page, navigating to it without a reload throws the error ...subscribe is not a function
. This makes sense because I am returning an object instead of an HTTP request.
Therefore, I attempted to modify the get method to simply return the object without making an HTTP request.
Updated get method in objectService:
get(): any {
if (this.object == undefined || this.object == null) {
return this.http.get(this.baseUrl + "/companies/get)
.map((data: any) => {
this.object = data;
});
}
return this.object;
}
Using the service to set page title with updated method:
ngOnInit() {
this.title.setTitle(this.objectService.get().name);
}
Now, the issue has shifted where a page refresh results in an error stating that this.objectService.get().name is undefined. However, when navigating to the component without a page refresh, it functions correctly.
If you have any suggestions on resolving this issue, please share your insights. Thank you in advance!