是否可以为带有注释的服务提供生命周期挂钩@Injectable()?
我曾经期望在这样的服务上调用生命周期钩子,但我被证明是错误的,它似乎@Component只是在工作.当依赖注入创建/销毁服务时,有没有办法在服务中获得信息?
import {Component, Injectable, OnInit, OnDestroy} from 'angular2/core';
@Injectable()
export class SampleService implements OnInit, OnDestroy {
ngOnInit() {
console.log("OnInit")
}
ngOnDestroy() {
console.log("OnDestroy")
}
}
@Component({
selector: "sample",
template: "<div>Sample Component</div>",
providers: [ SampleService ]
})
export class SampleComponent {
constructor() { private _sampleService: SampleService }
}
Run Code Online (Sandbox Code Playgroud) 我正在构建一个版本为beta.8的Angular 2应用程序.
在这个应用程序中,我有一个实现OnInit的组件.
在这个组件中我有函数ngOnInit,但从不调用ngOnInit函数.
import { Component, OnInit } from 'angular2/core';
@Component({
templateUrl: '/app/html/overview.html'
})
export class OverviewComponent implements OnInit {
ngOnInit() {
console.log('ngOnInit');
}
}
Run Code Online (Sandbox Code Playgroud)
应用程序的路由:
@RouteConfig([
{
path: '/overview',
name: 'Overview',
component: OverviewComponent
},
{
path: '/login',
name: 'Login',
component: LoginComponent
},
{
path: '/register',
name: 'Register',
component: RegisterComponent,
useAsDefault: true
}
])
Run Code Online (Sandbox Code Playgroud)
检查用户是否已登录LoginComponent和RegisterComponent.
如果用户已登录,则组件将使用以下方式重定向到Overview : router.navigate(['Overview']).
如果我使用Overview路由作为默认路由,我会在控制台中看到ngOnInit.
所以我重定向我的页面的方式似乎是问题.
如何重定向到Overview页面并调用ngOnInit函数?
无论是RegisterComponent和LoginComponent使用
ngOnInit() {
this._browser.getStorageValue('api_key', api_key => {
if (api_key) {
this._browser.gotoMain();
}
}) …Run Code Online (Sandbox Code Playgroud) Angular 5
什么时候创建和销毁服务,它的生命周期挂钩(如果有的话)是什么,它的数据如何在组件之间共享?
编辑:澄清一下,这不是关于组件生命周期的问题.这个问题是关于服务的生命周期.如果服务没有生命周期,那么组件和服务之间的数据流如何管理?
我已经实现了以下控制台输出,以跟踪执行的内容和不执行的内容./ dataList下的页面代码.
export class DataList implements OnInit {
constructor(private service: DataService) {
console.log("constructed");
}
ngOnInit() {
console.log("inited");
...
}
}
Run Code Online (Sandbox Code Playgroud)
现在,它通过输入URL以及使用来自另一个页面的路由访问页面时在控制台中提供输出(即构造和引入)两者的工作原理,如下所示.
this.router.navigateByUrl("/dataList");
Run Code Online (Sandbox Code Playgroud)
但是,当我从此页面导航到详细页面(使用/ dataElement/12345之类的URL ,其中12345是ID)时,它不显示已启动(仅构造),然后返回到执行导航的页面/ dataList通过上面显示的URL.(如果我然后点击F5,我会看到构造和inited,但是.)
我认为甚至不可能进入构造函数而不进入ngOnInit,给定实现的接口,但显然,我错了(并且也非常困惑).
我可以做的最好的诊断是,当从子路径路径导航时,不会调用初始化.但它对我来说似乎很奇怪,所以我怀疑我没有正确诊断它.谷歌搜索没有产生任何我认为充分相关的东西(像这样或者这样).路由就像这样.
const routes: Routes = [
{ path: "", component: StartComponent },
{ path: "dataList", component: DataListComponent },
{ path: "dataElement/:id", component: DataElementComponent …Run Code Online (Sandbox Code Playgroud)