angular - 在某些组件类的构造函数中,“this”包含类本身而不是实例
问题描述
我是 Angular 的新手,正在尝试与同事一起为 Angular 项目贡献更多组件。尽我最大的努力遵循最佳实践,所以我在组件的构造函数中所做的唯一事情就是存储来自依赖服务的必要数据。但是,我的代码表现不同。
我确信在调试器中所有依赖项都按预期工作,但“this”奇怪地指的是组件本身,而不是它的实例。
// the component
import { Component, OnInit } from '@angular/core';
import { SomeService } from '../some.service';
// and many other imports
@Component({
selector: 'app-some-component',
templateUrl: './some.component.html',
styleUrls: ['./some.component.sass']
})
export class SomeComponent implements OnInit {
someProperty: any;
constructor(
some: SomeService
// and many other dependencies
) {
this.someProperty = some.doSomethingQuick(); // <-- `this` refers to the ctor itself
// binding, transforming the data from the dependencies
}
ngOnInit() {
}
}
// the service
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SomeService {
constructor() { }
doSomethingQuick() {
// ...
}
}
我还调试了其他好的组件,当它由createView
它创建时返回实例,但就我而言,它返回 ctor 本身。太令人沮丧了。有人可以解释一下到底是什么吗?
解决方案
两种可能:
用ngOnInit(){}
方法:
// the component
import { Component, OnInit } from '@angular/core';
import { SomeService } from '../some.service';
// and many other imports
@Component({
selector: 'app-some-component',
templateUrl: './some.component.html',
styleUrls: ['./some.component.sass']
})
export class SomeComponent implements OnInit {
someProperty: any;
constructor(
some: SomeService
// and many other dependencies
) {}
ngOnInit() {
this.someProperty = this.some.doSomethingQuick();
}
}
或直接在声明中:
// the component
import { Component, OnInit } from '@angular/core';
import { SomeService } from '../some.service';
// and many other imports
@Component({
selector: 'app-some-component',
templateUrl: './some.component.html',
styleUrls: ['./some.component.sass']
})
export class SomeComponent implements OnInit {
someProperty = this.some.doSomethingQuick();
constructor(
some: SomeService
// and many other dependencies
) {}
ngOnInit() {}
}
推荐阅读
- c - 如何从 C 中的宏之类的函数中仅提取已定义函数的名称?
- node.js - 如何访问在不同容器上运行的两个快速服务器之间的不同端点
- swift - 在 init() 构造函数中初始化的带有 @State 的 SwiftUI 视图
- android - 无法在 android studio 3.6 中进行 git pull
- android - 适用于 Android 和 iOS 的应用内购买撤销机制
- ios - 需要在 Swift 中以编程方式进行监督和非监督
- r - Aggregate rows with conditions, sum quantitative values, and keep character values of the max
- android - APK分析使用MobSF(Mobile-Security-Framework-MobSF)框架,显示代码分析为空
- python - 用反斜杠 pandas 分隔列值
- android - Android Q 中的内部应用程序音频捕获不适用于某些 android 设备