如果站在相同的组件Angular 4,则通过添加侦听器进行路由

时间:2018-02-12 12:04:05

标签: angular routing

我会在两个产品之间导航,localhost:4200/products/444localhost:4200/products/555

当我在它们之间导航时,网址会发生变化,但DOM没有发生任何变化,我仍然停留在444产品,网址为555

我正在使用Angular 4

2 个答案:

答案 0 :(得分:1)

这是因为Angular重用了该组件。

您必须订阅路线参数以监听更改并相应地更新视图。

TASK [deploy_aker : Copy SSH key L2 users to host] ****************************************************************************************************************************************************************
fatal: [test.florius.com]: FAILED! => {"changed": false, "checksum": "cfcc6cdae818178456c4eca8e89ebce0c14ec91b", "msg": "Destination directory /home/[u'test1', u'test2', u'test3', u'test4']/.ssh does not exist"}

答案 1 :(得分:0)

让您的组件看起来像这样:

您必须从constructor调用您的函数。

您需要获取ID并从ngOnInit调用该函数。

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-comp',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  constructor(private route: ActivatedRoute) {
      this.myFunction(this.myID); // Remove this line from constructor     
    }

  ngOnInit() {
    this.route.params.subscribe(params => {
      this.myID = params['id'];
      this.myFunction(this.myID); // Add your function call in ngOnInit
    });
  }
}

要了解constructorngOnInit之间的区别,请click here