Angular2 RC1 - 调用组件时会触发哪个事件?

时间:2016-05-26 14:13:46

标签: angular angular2-routing

我有一个产品组件,访问beow url显示产品列表:

/products

产品页面中有分页,因此用户可以单击页面末尾显示的下一个/上一个链接。单击第一页上的“下一步”将用户移至以下URL:

/products/2

在我的组件中,我已经实现了ngOnInit,它根据我们当前所在的页面获取产品列表。

在Beta版本中,我使用CanReuse钩子使其工作。但是在当前版本中,当我单击下一页时,因为第2页没有调用ngOnInit,所以它不会获取产品列表。

我在某处读到CanReuse将在未来的更新中添加,我想知道有没有更好的方法来实现这一目标?

2 个答案:

答案 0 :(得分:1)

您可以在您可以订阅的组件中注入Router并使用它changes EventEmitter

然后,您可以使用location.path()来读取当前路径,例如switch case。像这样:

...
constructor(private _location:Location, private _router:Router) {
    _router.changes.subscribe( () => {
        switch(this._location.path()){
            case '/products':
                 // do some stuff...
                 break;
            case '/products/2':
                // do something different...
                break;
            default:
                // do nothing..
        }
    });

答案 1 :(得分:0)

免责声明:我的英语非常糟糕。

我做了一些测试,当你第二次进入时触发的事件是AfterViewInit

您可以像这样实现:

import {Component,AfterViewInit } from '@angular/core';

import {DataTableComponent} from '../../../shared/data-table/datatable.component.ts';

@Component({
    template: require('./consultorios-list.component.html'),
    styles: [require('./consultorios-list.component.scss')],
    directives: [DataTableComponent]
})

export class ConsultoriosListComponent implements OnInit {
    private datos:any = {
        titles: null, data: null
    };

    ngAfterViewInit(){
        console.log('I was printed when you enter to this route is showed c:');
    }
    constructor() {

    }
}

享受我的朋友。