Reputation: 13206
I am trying to subscribe to the following method which reads data from a json file:
getDefaultNavbarStyle(templateId): any {
let template = null;
switch (templateId) {
case ActiveTemplates.Default:
this.httpClient.get(this.DEFAULT_TEMPLATE_PATH).subscribe(response => {
template = response;
});
break;
case ActiveTemplates.Quick:
this.httpClient.get(this.QUICK_TEMPLATE_PATH).subscribe(response => {
template = response;
});
break;
case ActiveTemplates.Front:
this.httpClient.get(this.FRONT_TEMPLATE_PATH).subscribe(response => {
template = response;
});
break;
default:
break;
}
return template;
}
From another component:
this.defaultNavbarStyleSubscription = this.builderNavbarService.getDefaultNavbarStyle(this.navbarTemplate).subscribe(response => {
if (response) {
this.defaultNavbarStyle = response;
}
});
However, I keep getting the following error:
ERROR TypeError: Cannot read property 'subscribe' of null
What can I do to fix it? I've initialized template as null but set its value in the switch statement.
Upvotes: 0
Views: 1228
Reputation: 5181
By having a method to make a request you are usually return the Observable<any>
to subscribe to it as a caller:
Change it to:
Method:
getDefaultNavbarStyle(templateId): Observable<any> {
switch (templateId) {
case ActiveTemplates.Default:
return this.httpClient.get(this.DEFAULT_TEMPLATE_PATH)
case ActiveTemplates.Quick:
return this.httpClient.get(this.QUICK_TEMPLATE_PATH)
case ActiveTemplates.Front:
return this.httpClient.get(this.FRONT_TEMPLATE_PATH)
}
}
Caller:
this.defaultNavbarStyleSubscription = this.builderNavbarService.getDefaultNavbarStyle(this.navbarTemplate).subscribe(response => { this.defaultNavbarStyle = response; });
Upvotes: 1
Reputation: 11951
just add template =
to each case and erase .subscribe
case ActiveTemplates.Default:
return this.httpClient.get(this.DEFAULT_TEMPLATE_PATH);
case ActiveTemplates.Quick:
return ...
Upvotes: 1