在某些组件类的构造函数中,“ this”保存类本身而不是实例

时间:2019-09-03 15:00:12

标签: angular

我是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本身。真令人沮丧有人可以解释到底是什么吗?

1 个答案:

答案 0 :(得分:0)

两种可能性:

使用 public void Decompress(byte[] byteArray) { Stream inStream = new MemoryStream(byteArray); Stream gzipStream = new GZipInputStream(inStream); TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream); tarArchive.ExtractContents(@"."); tarArchive.Close(); gzipStream.Close(); inStream.Close(); } 方法:

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