inject() must be called from an injection context error

Discussão em 'Angular' iniciado por Tom H, Fevereiro 19, 2025.

  1. Tom H

    Tom H Guest

    I'm just learning Angular, so my apologies if I've missed something obvious.

    I have a simple login component which I'm using in my main page. Here's the login.component.html:

    @if (isLoggedIn) {
    <div>{{ loginName }}</div>
    }
    @else {
    <div (click)="signInWithGoogle()">Log In</div>
    }


    and the login.component.ts:

    import { Component, inject, ProviderToken } from '@angular/core';
    import { AuthGoogleService } from '../services/auth-google.service';

    @Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrl: './login.component.css',
    standalone: true,
    providers: [AuthGoogleService],
    })
    export class LoginComponent {
    private authService: AuthGoogleService;
    isLoggedIn: boolean = false;
    loginName: string = '';

    signInWithGoogle() {
    this.authService.login();
    }

    constructor() {
    this.authService = inject(AuthGoogleService);
    this.isLoggedIn = false;
    }
    }


    I've included the inject in the constructor exactly as the documentation suggests. I've also tried setting it in the declaration with the same results. In all cases I get the error stated in the question title. If I remove my component from the app.component.html then everything runs fine, so I'm pretty sure that the problem is with this component.

    Is there a way to debug the actual cause for this? Other things that I should be looking at? I'm currently using Angular 19.x.

    Continue reading...

Compartilhe esta Página