Angular 2 相当于 window.location.href?

标签 angular angular-new-router

如何在 Angular 2 中导航到不同的 URL?我知道我们可以使用 JavaScript 的

window.location.href = '...';

但这似乎是错误的并且会导致页面刷新。我很确定 Angular 2 中应该有允许您在 URL 之间移动而无需刷新页面的功能。我似乎无法在文档中找到它。

提前致谢!

最佳答案

根据文档,您可以使用Router 及其navigate 功能来更改当前状态,并在必要时传递参数:

import {Component, ...} from 'angular2/angular2';
import {Router, ...} from 'angular2/router';
import {HomeCmp} from '../home/home';

@Component({
  selector: 'app',
  // params of your component here
})
@RouteConfig([
  { path: '/', component: HomeCmp, as: 'MyHome' },
  // your other states here
])

export class AppCmp {
  router: Router;
  constructor(router: Router) {
    this.router = router;
  }
  navigateToHome() {
    // for example, that's how we can navigate to our home route
    this.router.navigate(['./MyHome', {param: 3}]);
  }
}

这是 official documentation 的链接.

这是一个 link以使用 Router 的一个很好的例子来播种项目。

关于Angular 2 相当于 window.location.href?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33323049/

相关文章:

angularjs - Angular 新路由器是 1.5 版本的一部分

angular - 如何在 ionic 3 中使用 Angular 6?

android - 在 chrome 开发工具上模拟低分辨率设备

在设置 compileComponents 变量之前运行的 Angular2 测试

javascript - Angular 新路由器从 URL 中删除/#

Angular 2 - 相当于路由器解析新路由器的数据

angular - 如何在 PhpStorm/WebStorm 中调试 angular2 种子项目?

angular - 当应用于 Angular 中的嵌套网格时,Mat-Table 数据源被覆盖

angularjs - 如何在 Angular 1.5 中注入(inject)组件路由器?