简体   繁体   English

注射不适用于角度应用

[英]The injection is not working in angular application

I have an Angular application nested in the MVC application. 我在MVC应用程序中嵌套了一个Angular应用程序。 I'm trying to extract it and have it as a stand-alone application. 我正在尝试提取它并将其作为独立的应用程序。

I created a new angular application, minimal version using CLI, copied my package.json, installed all packages, added a few components from the existing application, it builds and serves but when I try to run it I get an injection-related error. 我使用CLI创建了一个新的角度应用程序(最低版本),复制了package.json,安装了所有程序包,并从现有应用程序中添加了一些组件,它可以构建并提供服务,但是当我尝试运行它时,会遇到与注入相关的错误。

Here are samples of my code package.json , app.module.ts , app.config.ts , privacy.component.ts , app-routing.module.ts 这是我的代码package.jsonapp.module.tsapp.config.tsprivacy.component.tsapp-routing.module.ts app.module.ts

package.json package.json

{
  "name": "myApplication",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@agm/core": "^1.0.0-beta.5",
    "@alyle/ui": "^1.9.9",
    "@angular/animations": "^7.1.4",
    "@angular/cdk": "^7.3.7",
    "@angular/common": "~7.1.4",
    "@angular/compiler": "~7.1.4",
    "@angular/core": "^7.1.4",
    "@angular/forms": "~7.1.4",
    "@angular/http": "~7.1.4",
    "@angular/material": "^7.2.0",
    "@angular/material-moment-adapter": "^7.2.0",
    "@angular/platform-browser": "~7.1.4",
    "@angular/platform-browser-dynamic": "~7.1.4",
    "@angular/router": "~7.1.4",
    "@ngrx/router-store": "^8.1.0",
    "@ngrx/store": "^8.1.0",
    "angular-gauge": "^3.1.1",
    "angular2-resizing-cropping-image": "^1.0.0",
    "chroma-js": "^2.0.2",
    "classlist.js": "^1.1.20150312",
    "core-js": "^2.6.1",
    "hammerjs": "^2.0.8",
    "jquery-validation": "^1.19.0",
    "moment": "^2.23.0",
    "ngx-bar-rating": "^1.1.0",
    "ngx-cookie-service": "^2.1.0",
    "ngx-google-places-autocomplete": "^2.0.4",
    "oidc-client": "^1.8.2",
    "rxjs": "~6.3.3",
    "rxjs-compat": "^6.5.2",
    "tslib": "^1.9.0",
    "web-animations-js": "^2.3.1",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.11.0",
    "@angular/cli": "~7.1.4",
    "@angular/compiler-cli": "~8.1.0",
    "@angular/language-service": "~7.1.4",
    "@types/jasmine": "~3.3.4",
    "@types/jasminewd2": "~2.0.6",
    "@types/node": "~10.12.18",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~3.3.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.1.4",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.4",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.1",
    "ts-node": "~7.0.1",
    "tslint": "^5.12.0",
    "typescript": "~3.4.3"
  }
}

app.module.ts app.module.ts

import { BrowserModule, Title } from '@angular/platform-browser';
import { NgModule, Injectable } from '@angular/core';
import { MaterialModule } from './material.module';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { PrivacyComponent } from "./shared/privacy/privacy.component";
import { AppConfig } from './app.config';

@NgModule({
  declarations: [
    AppComponent,

    PrivacyComponent        
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    MaterialModule
  ],
  providers: [AppConfig],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.config.ts app.config.ts

import { Injectable } from "@angular/core";

@Injectable({
    providedIn: 'root'
})
export class AppConfig {

    constructor() {}

    siteName: string = "Site Name";
    siteUrl: string = "siteurl.com";
}

privacy.component.ts privacy.component.ts

import { Component, OnInit } from '@angular/core';
import { AppConfig } from '../../app.config';

@Component({
    selector: 'app-privacy',
    templateUrl: './privacy.component.html',
    styleUrls: ['./privacy.component.css']
})
export class PrivacyComponent implements OnInit {

    siteName: string = this.config.siteName;
    siteUrl: string = this.config.siteUrl;

    constructor(private config: AppConfig
        ) { }

    ngOnInit() {

    }
}

app-routing.module.ts app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { PrivacyComponent } from "./shared/privacy/privacy.component";

const routes: Routes = [
  { path: "", component: PrivacyComponent},
  { path: "privacy", component: PrivacyComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

When I try to access the page I'm getting the 当我尝试访问该页面时,

compiler.js:2193 Uncaught Error: Can't resolve all parameters for PrivacyComponent: (?).
    at syntaxError (compiler.js:2193)
    at CompileMetadataResolver._getDependenciesMetadata (compiler.js:17643)
    at CompileMetadataResolver._getTypeMetadata (compiler.js:17539)
    at CompileMetadataResolver.getNonNormalizedDirectiveMetadata (compiler.js:17168)
    at CompileMetadataResolver._getEntryComponentMetadata (compiler.js:17738)
    at compiler.js:17730
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver._getEntryComponentsFromProvider (compiler.js:17729)
    at compiler.js:17700
    at Array.forEach (<anonymous>)
syntaxError @ compiler.js:2193
_getDependenciesMetadata @ compiler.js:17643
_getTypeMetadata @ compiler.js:17539
getNonNormalizedDirectiveMetadata @ compiler.js:17168
_getEntryComponentMetadata @ compiler.js:17738
(anonymous) @ compiler.js:17730
_getEntryComponentsFromProvider @ compiler.js:17729
(anonymous) @ compiler.js:17700
_getProvidersMetadata @ compiler.js:17663
(anonymous) @ compiler.js:17665
_getProvidersMetadata @ compiler.js:17663
(anonymous) @ compiler.js:17295
getNgModuleMetadata @ compiler.js:17286
getNgModuleSummary @ compiler.js:17226
(anonymous) @ compiler.js:17308
getNgModuleMetadata @ compiler.js:17286
_loadModules @ compiler.js:24229
_compileModuleAndComponents @ compiler.js:24212
compileModuleAsync @ compiler.js:24174
compileModuleAsync @ platform-browser-dynamic.js:214
compileNgModuleFactory__PRE_R3__ @ core.js:20711
bootstrapModule @ core.js:20935
./src/main.ts @ main.ts:11
__webpack_require__ @ bootstrap:78
0 @ main.ts:12
__webpack_require__ @ bootstrap:78
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.js:1

which looks like related to the AppConfig that I'm trying to inject. 看起来与我要注入的AppConfig有关。 Not sure what I'm missing. 不知道我在想什么。

As mentioned by ritaj , if you've providedIn: 'root' , the service would be provided on the Root Injector. ritaj所提到的,如果您providedIn: 'root'In providedIn: 'root' ,则该服务将在Root Injector上提供。 In that case, you don't have to provide the service explicitly by adding it to the providers array. 在这种情况下,您不必通过将其添加到providers数组来显式提供服务。

It generally works just fine. 它通常可以正常工作。 But just to be on the safe side, get rid of that, and your app should work just fine: 但是为了安全起见,请摆脱这一点,您的应用程序应该可以正常运行:

import { BrowserModule, Title } from '@angular/platform-browser';
import { NgModule, Injectable } from '@angular/core';
import { MaterialModule } from './material.module';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { PrivacyComponent } from "./shared/privacy/privacy.component";
import { AppConfig } from './app.config';

@NgModule({
  declarations: [
    AppComponent,

    PrivacyComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    MaterialModule
  ],
  // providers: [AppConfig],  // COMMENT THIS LINE
  bootstrap: [AppComponent]
})
export class AppModule { }

Here's a Working Sample StackBlitz for your ref. 这是供您参考的工作样本StackBlitz

I see a mistake here, you're trying to access this.config before injecting service in to constructor. 我在这里看到一个错误,您正在尝试在将服务注入到构造函数之前访问this.config

export class PrivacyComponent implements OnInit {
    // First declare variables
    siteName: string ;
    siteUrl: string ;
    constructor(private config: AppConfig) {
     // And then assign values here

    siteName = this.config.siteName;
    siteUrl = this.config.siteUrl;
 }

    ngOnInit() {

    }
}

And usually you should name service accordingly ConfigurationService and then inject in constuctor with same name but with first letter in lower case 通常,您应该相应地将服务命名为ConfigurationService ,然后以相同的名称但以小写首字母的形式注入构造器

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})

export class ConfigurationService {
  serverUrl = 'https://my-website.com';
  siteName = 'Your site'

  constructor() {} 
}

// And here is component where do you need ConfigurationService

export class MyComponent{
  serverUrl;
  siteName;

  constructor(private configurationService: ConfigurationService  ) {
     this.serverUrl = this.configurationService.serverUrl;
     this.siteName = this.configurationService.siteName;
  } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM