首页 > 解决方案 > 在某些组件类的构造函数中,“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 本身。太令人沮丧了。有人可以解释一下到底是什么吗?

标签: angular

解决方案


两种可能:

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() {}
}

推荐阅读