为什么注射对儿童 class 不起作用?

Why injection does not work in child class?

我有单音class:

@Injectable({
    providedIn: 'root',
})
export class Services {
    public Service1 = new Service1();
}

Service1整个class是:

import { HttpRequests } from './http';
import { RepositoryModel } from './repository';
import { HttpClient } from '@angular/common/http';
    export class Service1 {
        public http: HttpRequests;
        public repositoryModel: RepositoryModel;

        constructor(private httpClient?: HttpClient) {
            console.log(httpClient);
            this.repositoryModel = new RepositoryModel();
            this.http = new HttpRequests(this.httpClient, this.repositoryModel);
        }
    }

为什么我在线获得 undefinedconsole.log(httpClient); 尽管我在 app.module 中有 httpClientModule

使用是:

 constructor(private services: Services) {}

因为您通过构造函数而不是通过 bean 创建来创建 Service1。 您有 2 个解决方案。通过服务的构造函数将 HttpClient 注入 Service1:

@Injectable({
providedIn: 'root',
})
export class Services {

    private service1: Service1;

    constructor(private httpClient?: HttpClient){
        this.service1 = new Service1(this.httpClient);
    }
}

或将 Service1 更改为 bean

@Injectable({
    providedIn: 'root',
})
export class Services {

constructor(private service1: Service1) {
    }
}


import { HttpRequests } from './http';
import { RepositoryModel } from './repository';
import { HttpClient } from '@angular/common/http';

@Injectable({
    providedIn: 'root',
})
export class Service1 {
public http: HttpRequests;
public repositoryModel: RepositoryModel;

constructor(private httpClient?: HttpClient) {
    console.log(httpClient);
    this.repositoryModel = new RepositoryModel();
    this.http = new HttpRequests(this.httpClient, this.repositoryModel);
    }
}