使用解决Angular2路线 [英] Using Resolve In Angular2 Routes

查看:414
本文介绍了使用解决Angular2路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在角1我的配置是这样的:

In Angular 1 my config looks like this:

$routeProvider
  .when("/news", {
    templateUrl: "newsView.html",
    controller: "newsController",
    resolve: {
        message: function(messageService){
            return messageService.getMessage();
    }
  }
})

如何使用决心Angular2?

How use resolve in Angular2?

感谢

推荐答案

由于alexpods已经提到的,似乎没有成为一个解析本身。这个想法似乎是你使用路由器提供生命周期挂钩的。它们是:

As alexpods has already mentioned, there doesn't seem to be a 'resolve' as such. The idea seems to be that you make use of the lifecycle hooks that the router provides. These are:


  • canReuse

  • canDeactivate

  • onActivate

  • onReuse

  • onDeactivate

再有就是 @CanActivate 。这是一个特殊的钩,因为你的组件进行实例化之前的叫法。它的参数是(下一个,previous)这是你路由到您所来自的组件和部件(或空,如果您有没有历史记录)分别。

Then there is @CanActivate. This is a special hook because it is called before your component is instantiated. Its parameters are (next, previous) which are the components you're routing to and the component you've come from (or null if you have no history) respectively.

import {Component} from 'angular2/angular2';
import {ROUTER_DIRECTIVES, CanActivate, OnActivate} from 'angular2/router';

@Component({
    selector: 'news',
    templateUrl: 'newsView.html',
    directives: [ROUTER_DIRECTIVES]
})

@CanActivate((next) => {
    return messageService.getMessage()
        .then((message) => {
            next.params.message = message;
            return true; //truthy lets route continue, false stops routing
        });
})

export class Accounts implements OnActivate {

    accounts:Object;

    onActivate(next) {
        this.message = next.params.message;
    }
}

我还没有想出是如何得到的承诺到onActivate结果的事情 - 不是将其存储你的'下一个'组件等。这是因为 onActivate 也只的下次的调用和的 previous 的和承诺没有结果。
我不开心与解决方案,但它是我能拿出最好的。

The thing I have not figured out yet is how to get the result of the promise into your onActivate - other than storing it on your 'next' component. This is because onActivate is also only invoked with next and previous and not the result of the promise. I'm not happy with that solution but it's the best I could come up with.

这篇关于使用解决Angular2路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆