角度-错误ReferenceError:未定义配置

时间:2018-11-28 12:21:37

标签: angular authentication authorization

我正在关注来自here.

的Angular 7身份验证和授权的教程

我已经添加了所有必需的文件,并且在ng服务期间也没有错误。 本教程还需要

declare var config: any;

要添加到Types.d.ts文件中。默认情况下,我的src目录中没有类型的文件。因此,我手动创建了类型的文件。并在其中添加了所需的声明。 Config分别用于2个服务中

在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;
            }));

和user.service.ts

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

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

在types.d.ts文件中添加声明后,编译器的错误消失了,但是当我运行应用程序并尝试登录时,在控制台上出现以下错误:

错误参考错误:未定义配置

详细日志:

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)

我已经尝试过类似的问题,但是它们并没有提供任何帮助。在这方面修复或解决配置的任何建议将受到高度赞赏。谢谢。

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);
    }
}

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}`);
    }
}

1 个答案:

答案 0 :(得分:2)

抱歉,为什么不使用其他方式呢?

将您的config.apiUrl放入constant or BETTER in your enviroment.ts file ..这样您就可以change the api url for different enviroment as you need ..

类似的东西

environment / environment.ts

export const environment = {

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

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

然后将其导入您的ts文件(如服务或您需要的任何文件中)..如:

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}`);
    }
}

希望它可以帮助您...

如果您仍然想要配置常量,请按照与环境相同的方式创建它。