【问题标题】:Angular2 injector causing Exception No Provier For Router errorAngular 2 注入器导致异常 No Provider For Router 错误
【发布时间】:2017-05-09 00:10:20
【问题描述】:

我的 Angular2 app.component.ts 中有以下代码

import { Component , OnInit} from '@angular/core';
import { WebService } from './webservices/webservices.services';
import { Http, Response } from '@angular/http';
import { Router } from '@angular/router';
import {HttpModule} from '@angular/http';
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  providers: [WebService]
})
export class AppComponent implements OnInit {

  //constructor(private http: Http,  private webservice: WebService/*, private router: Router*/) { }
  title: string = 'My first angular2-google-maps project';
  lat: number = 45.478418;
  lng: number = -122.209007;
  public ngOnInit(){

  }
/*  public getData(){
    this.webservice.getDataFromBackend()
      .subscribe(
      (data) => this.handleData(data),
     // (err) => this.logError(err),
      () => console.log('got data')
      );
  }

    private handleData(data: Response) {
    if (data.status === 200) {
      let receivedData = data.json();
      console.log(receivedData);
    }
    console.log(data.json());
  }
*/




}

当我取消注释构造函数时,我的浏览器中出现一堆错误(注释掉构造函数的工作),例如

例外:没有路由器提供程序! 和

错误:未捕获(承诺中):错误:DI 错误 BaseError@http://localhost:4200/vendor.bundle.js:25127:20 [角度]

。这是为什么呢?

编辑:app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ApplicationRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HttpModule } from '@angular/http';
import { AgmCoreModule } from 'angular2-google-maps/core';



@NgModule({
  imports: [
    BrowserModule,
    CommonModule,
    FormsModule,
    HttpModule,
    AgmCoreModule.forRoot({
      apiKey: 'Google Maps API Key'
    })
  ],
  providers: [],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

【问题讨论】:

  • 你能用你的根模块更新你的问题吗
  • 用 app.module.ts 更新

标签: angular dependency-injection angular2-services


【解决方案1】:

你忘记导入RouterModule

@NgModule({
  imports: [
  BrowserModule,
  CommonModule,
  FormsModule,
  HttpModule,
  RouterModule // <== here
  // ...
  ],
})

【讨论】:

  • 啊,我知道了我需要添加RouterModule.forRoot([ { path: 'maps', component:AppComponent } ]),
猜你喜欢
  • 2016-09-01
  • 2019-01-14
  • 1970-01-01
  • 2018-05-31
  • 1970-01-01
  • 2018-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多