Angular Injected服务未分配给对象实例

时间:2018-12-13 03:57:28

标签: angular angular6

我正在使用Angular6,我有这个:

'use strict';

import {ChangeDetectorRef, Component, OnInit} from '@angular/core';
import {MainService} from "./services/main.service";
import {AppService} from "../../app.service";

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


  ms: MainService;

  constructor(
    ms: MainService,
    private ref: ChangeDetectorRef
  ) {


  }

  ngOnInit() {
  }

  onChange(val: string){
    console.log('here is the dropdown change:', val);
    this.ms.updateRoutes();
  }


}

不幸的是,当我调用this.ms.updateRoutes()时,出现此错误:

  

MainComponent.html:4错误TypeError:无法读取属性   'updateRoutes'未定义       在MainComponent.onChange(main.component.ts:31)       在Object.eval [作为handleEvent](MainComponent.html:4)

给我的印象是我不必打电话

this.ms = ms;

在构造函数中?

1 个答案:

答案 0 :(得分:1)

您需要更改

constructor(
  ms: MainService,
  private ref: ChangeDetectorRef
) {

constructor(
  public ms: MainService,
  private ref: ChangeDetectorRef
) {

这告诉TypeScript编译器您希望ms自动成为类变量。