当注射类实例化ngOnInit不会被调用 [英] ngOnInit not being called when Injectable class is Instantiated
问题描述
任何想法,为什么 ngOnInit()
当注射
类解决就不叫?
code
进口{注射,OnInit中}从'angular2 /核心;
进口{RestApiService,RestRequest}从'./rest-api.service';@Injectable()
出口类MovieDbService实现的OnInit { 构造函数(私人_movieDbRest:RestApiService){
window.console.log('FROM构造函数()');
} ngOnInit(){
window.console.log('FROM ngOnInit()');
} 公共getMovie(){任何
window.console.log('FROM getMovie())
this._movieDbRest.globalParameters ['API_KEY'] = MOVIE_DB_API_KEY;
this._movieDbRest.baseUrl = MOVIE_DB_BASE_URL;
VAR movieRequest =新RestRequest();
movieRequest.endPoint ='/发现/ tt1431045';
movieRequest.parameters ['EXTERNAL_SOURCE'] ='imdb_id';
VAR promiseToReturn:无极<字符串取代; promiseToReturn =新承诺<串GT;(解析= GT;
this._movieDbRest.executeRequest(movieRequest)。然后(电影= GT; {
解析(动画);
window.console.log(电影);
}
));
返回promiseToReturn;
}
}
控制台输出
从构造函数()
FROM getMovie()
生命周期挂钩,如的OnInit()
与指令和组件工作。他们不与其他类型的工作,像你的情况的服务。从文档:
一个组件已通过角本身管理的生命周期。角创建它,使得它,创建和呈现其子,时检查其数据绑定属性改变,从DOM移除之前将其摧毁。
指令和组件实例有一个生命周期的角度创建,更新,并破坏它们。
块引用>Any idea why
ngOnInit()
would not be called when anInjectable
class is resolved?Code
import {Injectable, OnInit} from 'angular2/core'; import { RestApiService, RestRequest } from './rest-api.service'; @Injectable() export class MovieDbService implements OnInit { constructor(private _movieDbRest: RestApiService){ window.console.log('FROM constructor()'); } ngOnInit() { window.console.log('FROM ngOnInit()'); } public getMovie(): any{ window.console.log('FROM getMovie()') this._movieDbRest.globalParameters['api_key'] = MOVIE_DB_API_KEY; this._movieDbRest.baseUrl = MOVIE_DB_BASE_URL; var movieRequest = new RestRequest(); movieRequest.endPoint = '/find/tt1431045'; movieRequest.parameters['external_source'] = 'imdb_id'; var promiseToReturn : Promise<string>; promiseToReturn = new Promise<string>(resolve => this._movieDbRest.executeRequest(movieRequest).then(movie => { resolve(movie); window.console.log(movie); } )); return promiseToReturn; } }
Console Output
FROM constructor() FROM getMovie()
解决方案Lifecycle hooks, like
OnInit()
work with Directives and Components. They do not work with other types, like a service in your case. From docs:A Component has a lifecycle managed by Angular itself. Angular creates it, renders it, creates and renders its children, checks it when its data-bound properties change, and destroys it before removing it from the DOM.
Directive and component instances have a lifecycle as Angular creates, updates, and destroys them.
这篇关于当注射类实例化ngOnInit不会被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!