Angular - ERROR ReferenceError: config is not defined

String Name

I'm following a tutorial of Angular 7 authentication and authorization from here.

I've added all the required files and there's no error during ng serve as well. The tutorial also requires

declare var config: any;

to be added to typings.d.ts file. By default there was no typings.d.ts file in my src directory so I manually created typings.d.ts and added the required declaration there. Config is being used in 2 services respectively

In Authentication.service.ts

login(username: string, password: string) {
        return this.http.post<any>(`${config.apiUrl}/users/authenticate`, { username, password })
            .pipe(map(user => {
                // login successful if there's a jwt token in the response
                if (user && user.token) {
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify(user));
                    this.currentUserSubject.next(user);
                }

                return user;
            }));

and in user.service.ts

 getAll() {
        return this.http.get<User[]>(`${config.apiUrl}/users`);
    }

    getById(id: number) {
        return this.http.get<User>(`${config.apiUrl}/users/${id}`);
    }

After adding the declaration in typings.d.ts file the error from compiler goes away but when I run the application and try to sign in I get the following error on console:

ERROR ReferenceError: config is not defined

Detailed log:

ERROR ReferenceError: config is not defined
    at AuthenticationService.push../src/app/auth/_services/authentication.service.ts.AuthenticationService.login (authentication.service.ts:23)
    at LoginComponent.push../src/app/login/login.component.ts.LoginComponent.onSubmit (login.component.ts:51)
    at Object.eval [as handleEvent] (LoginComponent.html:6)
    at handleEvent (core.js:10251)
    at callWithDebugContext (core.js:11344)
    at Object.debugHandleEvent [as handleEvent] (core.js:11047)
    at dispatchEvent (core.js:7710)
    at core.js:9190
    at SafeSubscriber.schedulerFn [as _next] (core.js:3563)
    at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:195)

I've tried similar questions but they do not state any help. Any suggestions to fix or work around config in this regard will be highly appreciated. Thank you.

Entire code for authentication.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { User } from '../_models';

@Injectable({ providedIn: 'root' })
export class AuthenticationService {
    private currentUserSubject: BehaviorSubject<User>;
    public currentUser: Observable<User>;

    constructor(private http: HttpClient) {
        this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
        this.currentUser = this.currentUserSubject.asObservable();
    }

    public get currentUserValue(): User {
        return this.currentUserSubject.value;
    }

    login(username: string, password: string) {
        return this.http.post<any>(`${config.apiUrl}/users/authenticate`, { username, password })
            .pipe(map(user => {
                // login successful if there's a jwt token in the response
                if (user && user.token) {
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify(user));
                    this.currentUserSubject.next(user);
                }

                return user;
            }));
    }

    logout() {
        // remove user from local storage to log user out
        localStorage.removeItem('currentUser');
        this.currentUserSubject.next(null);
    }
}

Entire code for users.service.ts

import { AuthenticationService } from './authentication.service';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../_models';

@Injectable({ providedIn: 'root' })
export class UserService {
    constructor(private http: HttpClient) { }

    getAll() {
        return this.http.get<User[]>(`${config.apiUrl}/users`);
    }

    getById(id: number) {
        return this.http.get<User>(`${config.apiUrl}/users/${id}`);
    }
}
federico scamuzzi

Sorry why don't use a different way .. like this:

put your config.apiUrl in a constant or BETTER in your enviroment.ts file .. so you can change the api url for different enviroment as you need ..

somthing like:

environment/environment.ts

export const environment = {

  apiUrl: 'http://localhost:3000/api/',

     // <-- HERE PUT OTHER CONFIG THAT CAN CHANGE FROM EENVIROMENT 
};

then import it in yours ts file (like service or any where you need it) .. like:

import { AuthenticationService } from './authentication.service';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../_models';
import { environment } from '../environment/environment';


@Injectable({ providedIn: 'root' })
export class UserService {
    constructor(private http: HttpClient) { }

    getAll() {
        return this.http.get<User[]>(`${environment.apiUrl}/users`);
    }

    getById(id: number) {
        return this.http.get<User>(`${environment.apiUrl}/users/${id}`);
    }
}

Hope it helps you ...

If you still want a config constant .. cfreate it in the same way as enviroment does

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Angular Error - ReferenceError: $modal is not defined

ERROR ReferenceError: $ is not defined at angular datatables

Alertify Error "ReferenceError: alertify is not defined " in Angular 6

Angular 7 ERROR ReferenceError: SystemJS is not defined

Angular with TypeScript: ReferenceError: System is not defined System.config

ReferenceError: angular is not defined in WebStorm

Uncaught referenceError : Angular is not defined

ReferenceError: $ is not defined jquery error

'ReferenceError: document is not defined' error

Error: ReferenceError: getUnreadEmails is not defined

ReferenceError:Users is not defined error

ReferenceError: Headers is not defined error

ReferenceError: $ is not defined - Modal error

Angular 9 SSR Build Serve eror -- ERROR ReferenceError: document is not defined

webpack+angular2 error: Uncaught ReferenceError: __decorate is not defined

Angular - Uncaught ReferenceError: angular is not defined

Angular SSR - ReferenceError: Element is not defined

ReferenceError: resolve is not defined after added the @ path config

ReferenceError: require is not defined using require("dotenv").config();

Uncaught ReferenceError: LoadFile is not defined Error

ReferenceError: event is not defined error in Firefox

Error in render: "ReferenceError: h is not defined"

Error: Uncaught ReferenceError: React is not defined

Console Error with Ajax: ReferenceError: $ is not defined

ReferenceError: nlapiLoadFile is not defined error In Netsuite

Error Uncaught ReferenceError: Morris is not defined

Leaflet error > ReferenceError: L is not defined

the error is "Uncaught ReferenceError: require is not defined" and Uncaught ReferenceError: ipcRenderer is not defined

ASP.NET CORE 2 + ANGULAR 4: NodeInvocationException: Prerendering failed because of error: ReferenceError: window is not defined