asp.net - 未捕获( promise ): Error: StaticInjectorError[Service]

标签 asp.net angular typescript visual-studio-2015 angular5

我是 Angular 的新手。我使用 vs2015 和最新的 Angular 包创建了一个网络应用程序。 当我尝试在按钮单击事件上从组件调用我的服务时,我在浏览器控制台窗口中遇到以下错误。

错误:-

ERROR Error: Uncaught (in promise): Error: StaticInjectorError[ViewCountService]: 
  StaticInjectorError[ViewCountService]: 
    NullInjectorError: No provider for ViewCountService!
Error: StaticInjectorError[ViewCountService]: 
  StaticInjectorError[ViewCountService]: 
    NullInjectorError: No provider for ViewCountService!
    at _NullInjector.get (injector.js:31)
    at resolveToken (injector.js:387)
    at tryResolveToken (injector.js:330)
    at StaticInjector.get (injector.js:170)
    at resolveToken (injector.js:387)
    at tryResolveToken (injector.js:330)
    at StaticInjector.get (injector.js:170)
    at resolveNgModuleDep (ng_module.js:103)
    at NgModuleRef_.get (refs.js:1037)
    at resolveDep (provider.js:455)
    at _NullInjector.get (injector.js:31)
    at resolveToken (injector.js:387)
    at tryResolveToken (injector.js:330)
    at StaticInjector.get (injector.js:170)
    at resolveToken (injector.js:387)
    at tryResolveToken (injector.js:330)
    at StaticInjector.get (injector.js:170)
    at resolveNgModuleDep (ng_module.js:103)
    at NgModuleRef_.get (refs.js:1037)
    at resolveDep (provider.js:455)
    at resolvePromise (zone.js:824)
    at resolvePromise (zone.js:795)
    at zone.js:873
    at ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (ng_zone.js:575)
    at ZoneDelegate.invokeTask (zone.js:424)
    at Zone.runTask (zone.js:192)
    at drainMicroTaskQueue (zone.js:602)
    at ZoneTask.invokeTask [as invoke] (zone.js:503)
    at invokeTask (zone.js:1540)
defaultErrorLogger @ errors.js:48
ErrorHandler.handleError @ error_handler.js:90
next @ application_ref.js:311
schedulerFn @ event_emitter.js:156
SafeSubscriber.__tryOrUnsub @ Subscriber.ts:254
SafeSubscriber.next @ Subscriber.ts:204
Subscriber._next @ Subscriber.ts:135
Subscriber.next @ Subscriber.ts:95
Subject.next @ Subject.ts:61
EventEmitter.emit @ event_emitter.js:131
(anonymous) @ ng_zone.js:605
ZoneDelegate.invoke @ zone.js:392
Zone.run @ zone.js:142
NgZone.runOutsideAngular @ ng_zone.js:404
onHandleError @ ng_zone.js:605
ZoneDelegate.handleError @ zone.js:396
Zone.runGuarded @ zone.js:158
_loop_1 @ zone.js:702
api.microtaskDrainDone @ zone.js:711
drainMicroTaskQueue @ zone.js:610
ZoneTask.invokeTask @ zone.js:503
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566

我的 app.module.ts: -

import { NgModule, Injectable } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';
import { HttpModule } from '@angular/http';


import { ModalModule } from 'ngx-modialog';
import { BootstrapModalModule, Modal, bootstrap4Mode } from 'ngx-modialog/plugins/bootstrap';

import { AppComponent } from './app.component';
import { ExportToPdfComponent } from './exportTopdf/exportTopdf.component';
import { InvalidPageComponent } from './invalidPage/invalidPage.component';

import { ViewCountService } from './Service/viewsCount.component';

const appRoutes: Routes = [
    { path: 'home', component: AppComponent },
    { path: '', redirectTo: '/home', pathMatch: 'full' },
    { path: 'export', component: ExportToPdfComponent },
    { path: '**', component: InvalidPageComponent }
];

@NgModule({
    imports: [
        BrowserModule,
        HttpModule,
        RouterModule.forRoot(appRoutes),
        ModalModule.forRoot(),
        BootstrapModalModule
    ],
    declarations: [
        AppComponent,
        ExportToPdfComponent,
        InvalidPageComponent
    ],
    bootstrap: [
        AppComponent
    ],
    providers: [
        ViewCountService
    ]
})



export class AppModule { }

exportTopdf.component.ts 文件:-

import { Component, ViewContainerRef, ViewEncapsulation } from '@angular/core';
import { ViewCountService } from '../Service/ViewsCount.component';

import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';

@Component({
    selector: 'export-to-pdf',
    templateUrl: 'app/exportTopdf/exportTopdf.component.html',
})
export class ExportToPdfComponent {
    name: string;
    fields: any;

    constructor(public modal: Modal, private ViewCountService: ViewCountService) {
        debugger;
        this.fields = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
    }


    getViewCount(): void {
        debugger;
        this.ViewCountService.getViewCount()
            .then(data => {
                this.name = data;
                console.log("I CANT SEE DATA HERE: ", this.name)
            });
    }

}

我的服务代码:-

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class ViewCountService {
    constructor(private http: Http) {
    }

    getViewCount() {
        return this.http.get('api/Tableau/GetViewsCount')
            .map(response => response.json() as string).toPromise();
    }

    getDataObservable(url: string) {
        return this.http.get('api/Tableau/GetViewsCount')
            .map(data => {
                data.json();
                console.log("I CAN SEE DATA HERE: ", data.json());
            });
    }

}

系统.config.js: -

/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
    System.config({
        transpiler: 'typescript',
        //typescript compiler options
        typescriptOptions: {
            emitDecoratorMetadata: true
        },
        paths: {
            // paths serve as alias
            'npm:': '/node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            'app': 'app',

            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

            // other libraries
            'rxjs': 'npm:rxjs',
            'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',

            'ngx-modialog': 'npm:ngx-modialog/bundle/ngx-modialog.umd.min.js',
            'ngx-modialog/plugins/bootstrap': 'npm:ngx-modialog/plugins/bootstrap/bundle/ngx-modialog-bootstrap.umd.min.js'


        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                defaultExtension: 'js',
                meta: {
                    './*.js': {
                        loader: 'systemjs-angular-loader.js'
                    }
                }
            },
            rxjs: {
                defaultExtension: 'js'
            }
        }
    });
})(this);

package.json: -

{
  "name": "angular-quickstart",
  "version": "1.0.0",
  "description": "QuickStart package.json from the documentation, supplemented with testing support",
  "scripts": {
    "build": "tsc -p src/",
    "build:watch": "tsc -p src/ -w",
    "build:e2e": "tsc -p e2e/",
    "serve": "lite-server -c=bs-config.json",
    "serve:e2e": "lite-server -c=bs-config.e2e.json",
    "prestart": "npm run build",
    "start": "concurrently \"npm run build:watch\" \"npm run serve\"",
    "pree2e": "npm run build:e2e",
    "e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first",
    "preprotractor": "webdriver-manager update",
    "protractor": "protractor protractor.config.js",
    "pretest": "npm run build",
    "test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
    "pretest:once": "npm run build",
    "test:once": "karma start karma.conf.js --single-run",
    "lint": "tslint ./src/**/*.ts -t verbose"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "~5.0.3",
    "@angular/compiler": "~5.0.3",
    "@angular/core": "~5.0.3",
    "@angular/forms": "~5.0.3",
    "@angular/http": "~5.0.3",
    "@angular/platform-browser": "~5.0.3",
    "@angular/platform-browser-dynamic": "~5.0.3",
    "@angular/router": "~5.0.3",
    "angular-in-memory-web-api": "~0.5.1",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "ngx-modialog": "^5.0.0",
    "rxjs": "5.5.2",
    "systemjs": "0.20.19",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "concurrently": "^3.2.0",
    "lite-server": "^2.2.2",
    "typescript": "~2.6.1",
    "canonical-path": "0.0.2",
    "tslint": "^5.8.0",
    "lodash": "^4.16.4",
    "jasmine-core": "~2.8.0",
    "karma": "^1.3.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.2.0",
    "rimraf": "^2.5.4",
    "@types/node": "^8.0.53",
    "@types/jasmine": "2.8.2"
  },
  "repository": {}
}

提前感谢您提出宝贵的反馈和意见。

最佳答案

看看你的进口商

app.module.ts

import { ViewCountService } from  './Service/viewsCount.component';

exportTopdf.component.ts

import { ViewCountService } from '../Service/ViewsCount.component';

因为 Systemjs 区分大小写(参见 Service instance is not available for child component in angular2 )

看起来你正在导入不同的模块

ViewsCount 
|
viewsCount

所以只选择一个选项来导入你的服务

app.module.ts

import { ViewCountService } from  './Service/viewsCount.component';

exportTopdf.component.ts

import { ViewCountService } from '../Service/viewsCount.component';
                                             ^
                                         instead of V

另请阅读 style guide更好地理解如何命名文件

关于asp.net - 未捕获( promise ): Error: StaticInjectorError[Service],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47549378/

相关文章:

javascript - 将数组显示为分页 View

javascript - 使用 webpack 重用 Fullstack 模块

typescript - 是否可以在 Jasmine 单元测试中修改或模拟 Typescript 类使用的 Inversify 容器?

asp.net - 如何在 Asp.Net 页面中包含 Javascript 文件

c# - ASP.net 在服务引用之间重用类型

c# - 使用 asp.net 成员(member)资格有哪些优点和缺点?

c# - 如何使用 twitter api 获取 twitter 用户的电子邮件地址

angular - 如何在焦点上显示自动完成选项

angular - 无法读取未定义的属性 'next'

javascript - babel 转译 typescript 文件后,要求路径不正确