ngOnInit()没有被触发

时间:2018-03-23 04:57:24

标签: angular typescript ionic-framework ionic3

我有以下文件:

/src/app/app.module.ts

...
@NgModule({
    ...
    providers: [
        StatusBar,
        SplashScreen,
        Storage,
        ConfigService,
        AuthService,
        TodoService,
    ]
    ...
})
export class AppModule { }

/src/providers/config.service.ts

import { Injectable } from '@angular/core';

export interface HashTable<T> {
    [key: string]: T;
}

@Injectable()
export class ConfigService {

    config: HashTable<String> = {
        'baseUrl': 'http://127.0.0.1:8080',
    };

    constructor() { }

    getConfig(): HashTable<String> {
        return this.config;
    }

}

/src/providers/todo.service.ts

import { Injectable, OnInit } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { ConfigService, HashTable } from './config.service';
import { AuthService } from './auth.service';
import 'rxjs/add/operator/map';

@Injectable()
export class TodoService implements OnInit {

    config: HashTable<String>;

    constructor(private http: Http, private configService: ConfigService, private authService: AuthService) {
        // this.getConfig();
    }
    ngOnInit() {
        this.getConfig();
    }
    getConfig(): void {
        this.config = this.configService.getConfig();
    }
    getTodos() {
        return new Promise((resolve, reject) => {
            let headers = new Headers();
            headers.append('Authorization', this.authService.token);
            this.http
                .get(
                    this.config['baseUrl'] + '/api/todos',
                    { headers: headers }
                )
                .map(res => res.json())
                .subscribe(
                    data => {
                        resolve(data);
                    },
                    err => {
                        reject(err);
                    }
                );
        });
    }
}

在文件中: todo.service.ts ...

ngOnInit()没有被触发。我需要这个来触发方法:this.getConfig()被调用。

另一方面,如果我取消注释构造函数中的行(同一文件),一切正常,但我不希望这样,因为我希望调用ngOnInit。我已经阅读了一些你应该调用服务负载的地方,在这种情况下:this.getConfig();内有ngOnInit

我的目标是使用文件存储应用程序的配置值。实际上,如果我取消构造函数中的行,但是我正在尝试调整标准,这段代码工作正常。

对此有什么想法吗?

感谢。

2 个答案:

答案 0 :(得分:2)

OnInit()使用指令和组件。它们不能与其他类型一起使用,例如服务。它不适用于Injectable类。 您的代码不适用于Lifecycle hooks

答案 1 :(得分:0)

ngOnInit()不适用于服务。

相同解释ngOnInit not being called when Injectable class is Instantiated

相关问题