I’m encountering an issue with Angular 17 where calling a function that has HttpClient injected using the inject function works from the constructor, but throws an error when called from an HTML button click.
Error Message
ERROR Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with
runInInjectionContext
. Find more at https://angular.io/errors/NG0203
at injectInjectorOnly (core.mjs:1093:15)
at ɵɵinject (core.mjs:1106:42)
at inject (core.mjs:1192:12)
at _JwtInterceptor.intercept (jwt.interceptor.ts:19:35)
at http.mjs:1722:58
at Object.handle (http.mjs:1723:34)
at fake-backend.ts:68:
**FooterComponent **
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { createdBy, developedByLink } from 'src/app/states/constants';
@Component({
selector: 'web-studio-footer',
standalone: true,
imports: [],
templateUrl: './footer.component.html',
styles: [],
})
export class FooterComponent {
author = createdBy;
developBy = developedByLink;
company = ['Home', 'Services', 'Projects', 'Blog'];
support = ['Help center', 'Terms of service', 'Legal', 'Privacy policy'];
public message: string | undefined;
// Use `inject` to obtain the HttpClient
public http = inject(HttpClient);
constructor() {
this.saludar(); // THIS WORKS
}
public saludar() {
console.log('saludar');
this.http.get('https://jsonplaceholder.typicode.com/posts/1').subscribe({
next: (data) => {
console.log(data);
},
});
}
}
footer.component.html
<button (click)="saludar()"
class="btn btn-primary rounded-pill"
type="button">
Contáctenme
</button>
The function works perfectly when called from the constructor, but it fails when triggered by a button click in the HTML.
Question
How can I call the saludar function from the HTML button click without encountering the NG0203 error? Is there a different way to inject the HttpClient or a specific context I should be aware of?
Any help would be greatly appreciated!
Eleazar Ramos Cortes is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.