【问题标题】:Angular - ERROR ReferenceError: config is not definedAngular - 错误 ReferenceError:未定义配置
【发布时间】:2019-04-30 08:33:40
【问题描述】:

我正在关注 here. 的 Angular 7 身份验证和授权教程

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

declare var config: any;

添加到 typings.d.ts 文件中。默认情况下,我的 src 目录中没有 typings.d.ts 文件,因此我手动创建了 typings.d.ts 并在那里添加了所需的声明。 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}`);
    }

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

ERROR ReferenceError: config is not defined

详细日志:

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

【问题讨论】:

  • 嗨..你能发布你所有的服务 ts 代码吗?
  • 完成。请检查。
  • 您是否已将 webpack.DefinePlugin 条目添加到您的 webpack 配置中?
  • @Sergio new webpack.DefinePlugin({ // 全局应用配置对象 config: JSON.stringify({ apiUrl: 'localhost:4200' }) }) 添加到 webpack.config.js

标签: angular authentication authorization


【解决方案1】:

对不起,为什么不使用不同的方式..像这样:

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

类似:

环境/环境.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}`);
    }
}

希望对你有帮助...

如果您仍然想要一个配置常量 .. 以与环境相同的方式创建它

【讨论】:

  • 没有想到这个办法。谢谢。像魅力一样工作。
  • 很高兴它帮助了你
猜你喜欢
  • 2020-02-15
  • 1970-01-01
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
  • 2019-09-08
  • 2020-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多