【问题标题】:Cannot read property 'navigate' of undefined error无法读取未定义错误的属性“导航”
【发布时间】:2021-07-18 04:56:48
【问题描述】:

下面是我的导航代码

         export class AppComponent {
           router:Router
            doSwipe(direction: string){

               this.router.navigate(['/article']);
            }
       }

我收到无法读取未定义错误的属性“导航”。请帮助修复它

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您需要注入路由器,而不仅仅是将其声明为属性

    constructor(private router: Router) {}
    

    【讨论】:

      【解决方案2】:

      在我的例子中,我使用@Inject 注解将路由器注入到构造函数中。

      constructor(@Inject(Router) private router: Router) {}
      

      【讨论】:

      • 为什么我们需要这个。使用@Inject(Router)有什么目的。因为不使用它可以正常工作。有什么区别吗?
      【解决方案3】:

      你需要在构造函数中注入Router

      export class AppComponent {
          constructor(
              private router: Router
          ) {}
      
          doSwipe(direction: string) {
      
              this.router.navigate(['/article']);
          }
      }
      

      【讨论】:

        【解决方案4】:

        你需要在constructor里面注入路由器,

        constructor(
             private router: Router
        ){
        
        }
        

        【讨论】:

          【解决方案5】:

          有点老了,但就我而言,我有 Fabio 的回答, 但忘记添加@autoInject()

          所以你必须添加

          import { autoinject } from 'aurelia-framework';
          
          @autoinject()
          export class YourClass {
               
               constructor(private router: Router) {}
          
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-12-05
            • 1970-01-01
            • 1970-01-01
            • 2020-02-04
            • 2020-09-26
            相关资源
            最近更新 更多