4

Rebuilding a demo login and registration page app in Angular following a tutorial I found here. Currently getting this

ERROR in src/app/_services/authentication.service.ts(10,35): error TS2304: Cannot find name 'config'

Searched for similar issues here and here. The first link addresses issues with webpack but is outdated and the second is completely unrelated. I've added "webpack-env" to both tsconfig.app.json & tsconfig.spec.json I've also updated webpack and webpack cli following these instructions.

See the affected code below: webpack.config.js

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/main.ts',
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: ['ts-loader', 'angular2-template-loader'],
        exclude: /node_modules/
      },
      {
        test: /\.(html|css)$/,
        loader: 'raw-loader'
      },
    ]
  },
  resolve: {
    extensions: ['.ts', '.js']
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      filename: 'index.html',
      inject: 'body'
    }),
    new webpack.DefinePlugin({
      // global app config object
      config: JSON.stringify({
        apiUrl: 'http://localhost:4000'
      })
    })
  ],
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
    runtimeChunk: true
  },
  devServer: {
    historyApiFallback: true
  }
};

authentication.service.ts

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

@Injectable()
export class AuthenticationService {
  constructor(private http: HttpClient) { }

  login(username: string, password: string) {
    return this.http.post<any>(`${config.apiUrl}/users/authenticate`, { username: username, password: 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));
        }

        return user;
      }));
  }

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

user.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

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

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

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

  register(user: User) {
    return this.http.post(`${config.apiUrl}/users/register`, user);
  }

  update(user: User) {
    return this.http.put(`${config.apiUrl}/users/` + user.id, user);
  }

  delete(id: number) {
    return this.http.delete(`${config.apiUrl}/users/` + id);
  }
}

tsconfig.app.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "module": "es2015",
    "types": [
      "webpack-env"
    ]
  },
  "exclude": [
    "src/test.ts",
    "**/*.spec.ts"
  ]
}

tsconfig.spec.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    "module": "commonjs",
    "types": [
      "jasmine",
      "node",
      "webpack-env"
    ]
  },
  "files": [
    "test.ts",
    "polyfills.ts"
  ],
  "include": [
    "**/*.spec.ts",
    "**/*.d.ts"
  ]
}
Brandon Brawley
  • 137
  • 3
  • 4
  • 8

1 Answers1

8

See Angular 6 Custom Typings File

Path: /src/typings.d.ts

A custom typings file is used to declare types that are created outside of your angular application, so the TypeScript compiler is aware of them and doesn't give you errors about unknown types. This typings file contains a declaration for the global config object that is created by webpack (see webpack.config.js below).

// so the typescript compiler doesn't complain about the global config object
declare var config: any;
Igor
  • 60,821
  • 10
  • 100
  • 175
  • Wow... I've been literally working on this for days and I completely missed that. So thanks. Now that I see it, how do I add it via the Angular CLI? Obviously, I can simply copy the file from his example but that won't help me in future projects? – Brandon Brawley Jul 10 '18 at 20:55
  • @BrandonBrawley - It's a typings file, you can copy paste this as it is not a true angular structure that you need to add using the cli. – Igor Jul 10 '18 at 20:56
  • what I am asking is, how do I add the typings.d.ts file? Once I create the file, I recognize I'll have to copy/paste. I've been looking around online and it just doesn't seem intuitive. The touch command doesn't work because of the Angular cli. – Brandon Brawley Jul 10 '18 at 21:25
  • @BrandonBrawley I don't know what your OS is but just do hire ever you manually create files in the correct directory. Angular will pick it up automatically at transpile time. – Igor Jul 10 '18 at 21:35
  • I figured it out. Thanks again. – Brandon Brawley Jul 10 '18 at 21:49