【问题标题】:How to debug Angular Service which doesn't inject [construct] itself?如何调试不注入 [construct] 本身的 Angular 服务?
【发布时间】:2017-09-16 12:08:50
【问题描述】:

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

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);
  }
}

…及其部门的模块(import: [ed by '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 { }

服务列在“app.module”中:

@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 设为静态,然后给我:TypeError: this.snackBar is undefined

My test-case 不会复制该错误。显然AlertsService 没有在这里构造/注入。 如何调试注入器?

【问题讨论】:

  • 不清楚问题是什么。什么是“[构造]”?你想调试它做什么? 没有复制错误 - 什么错误?
  • 哎呀,删掉了,等一下
  • providers 是在哪里定义的?它在这里是相关的,并且可能定义错误。
  • 用我的AppModule编辑。
  • 您可以使用 Augury Chrome 扩展程序对其进行调试,或者通过在this.alertsService 上记录或设置断点来进行调试,但看起来可以通过此处的定期健全性检查来解决。 将警报设为静态,然后给我:TypeError: this.snackBar is undefined - 这表明它被定义为{ provide: AlertsService, useValue: AlertsService }。如果你不能在你的测试用例中复制它,这意味着它在一个地方以一种方式完成,在另一个地方以另一种方式完成。

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


【解决方案1】:

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

绑定

.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 导入。

【讨论】:

  • 现在我也可以从我的代码库中取出所有 .bindAlertsService
猜你喜欢
  • 1970-01-01
  • 2021-07-23
  • 1970-01-01
  • 2014-09-19
  • 2020-06-13
  • 2017-06-18
  • 1970-01-01
  • 1970-01-01
  • 2020-12-21
相关资源
最近更新 更多