如何调试不注入[construct]本身的Angular Service?

时间:2017-09-16 12:08:51

标签: angular dependency-injection angular-services angular-decorator

我有一个非常简单的服务:

#include<stdio.h>

int main()
{
    int a,b,i,x,c,f=1;
    const char* delim = "";
    scanf("%d%d",&a,&b);
    for(x=a; x<=b; (x++,f=0))
    {
        for(i=2; i<x; i++)
        {
            if(x%i==0)
            {
                f=1;
                break; //no need to continue the checking
            }
        }

        if(f==0) {
            printf("%s%d",delim,x);
            delim = ", ";
        }
    }
    putchar('\n');
}

...及其dep的模块(import { Injectable } from '@angular/core'; import { MdSnackBar, MdSnackBarConfig } from '@angular/material'; @Injectable() export class AlertsService { alerts: string[]; constructor(private snackBar: MdSnackBar) { this.alerts = []; } public add(alert: string, action?: string, config?: MdSnackBarConfig) { this.alerts.push(alert); // console.warn('AlertsService::alerts =', this.alerts, ';'); this.snackBar.open(alert, action, config); } } 由'app.module'编辑):

import: [

服务列在'app.module'中:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MdSnackBarModule } from '@angular/material';

@NgModule({
  imports: [
    CommonModule, MdSnackBarModule
  ],
  exports: [
    MdSnackBarModule
  ]
})
export class AlertsModule { }

它的使用方式如下:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    CommonModule,
    BrowserModule,
    FormsModule,
    HttpModule,
    BrowserAnimationsModule,
    SomeComp1Module,
    AlertsModule
  ],
  providers: [
    AlertsService
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

错误

@Component({
  selector: 'app-some-comp1',
  templateUrl: './some-comp1.component.html'
})
export class SomeComp1Component {
  constructor(private alertsService: AlertsService) {
      this.alertsService.add('SomeComp1Component');
  }
}

TypeError: this.alerts is undefined 设为静态,然后给我:alerts

My test-case不会复制该错误。很明显TypeError: this.snackBar is undefined没有在这里构建/注入。 如何调试进样器?

1 个答案:

答案 0 :(得分:0)

以几种不同的方式解决它:

绑定

.catch(this.alertsService.add.bind(this.alertsService))

现在alertsService实际上向渲染的浏览器视图显示了正确的输出。

实例函数

有时仍然会收到TypeError: this.alerts is undefined(来自完全相同的上下文Comp0::func0::this.alertsService)所以决定尝试other TypeScript recommended solution

public add = (alert: string, action?: string, config?: MdSnackBarConfig) => {
    this.alerts.push(alert);
    this.snackBar.open(alert, action, config);
}

其他

这个this错误令我非常烦恼,以至于我重新生成了所有代码并用“细齿梳”将我原来的基地迁移回来。所以不确定它是否相关,但我发现了额外的BrowserAnimationsModule导入和一些rxjs/add次导入。