角度路由问题 - 路由不会像往常一样工作

时间:2021-06-08 13:33:10

标签: javascript angular

我遇到了一个问题,当我手动输入 localhost:4200/create 时,它​​会出现在我想要它去的页面上,但是当我单击链接将我带到那里时,我收到一条错误消息:

TypeError: Cannot read property 'unsubscribe' of undefined
    at PostListComponent.ngOnDestroy  

这是我的代码:

header.component.html

<mat-toolbar color="primary">
  <span><a routerLink="/">My Messages</a></span>
  <ul>
    <li><a routerLink="/create">New Post</a></li>
  </ul>
</mat-toolbar>

app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { PostCreateComponent } from './posts/post-create/post-create.component';
import { PostListComponent } from './posts/post-list/post-list.component';

const routes: Routes = [
  {path: '', component: PostListComponent},
  {path: 'create', component: PostCreateComponent},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

postlistcomponent.ts

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';

import { Post } from '../posts';
import { PostsService } from '../posts.service';

@Component({
  selector: 'app-post-list',
  templateUrl: './post-list.component.html',
  styleUrls: ['./post-list.component.css'],
})
export class PostListComponent implements OnInit, OnDestroy {
  
  posts: Post[] = [];
  private postsSub: Subscription;
  constructor(public postsService: PostsService) {}

  ngOnInit(): void {
    this.postsService.getPosts();
    this.postsService.getPostUpdateListener().subscribe((posts: Post[]) => {
      this.posts = posts;
    });
  }

  onDelete(postId: string) {
    this.postsService.deletePost(postId);
  }

  ngOnDestroy() {
    this.postsSub.unsubscribe();
  }
}

3 个答案:

答案 0 :(得分:3)

就像错误所说的那样,您正在对 unsubscribe 中不存在的对象调用 PostListComponent (postlist.component.ts?)

在该文件中,找到 ngOnDestroy 函数,对于任何 this.object$.unsubscribe() 函数,首先测试对象 -

if (this.object$ && !this.object$.closed) {
   this.object$.unsubscribe()
}

我以 this.object$ 为例 - 您的变量将被称为不同的名称

答案 1 :(得分:1)

当您从 / 导航到 /create 时,ngOnDestroy 中的 PostListComponent 会引发错误。

这就是为什么它发生在链接上而不是当你输入网址时。

答案 2 :(得分:1)

正如您在 ngInit 中看到的,您没有将任何值传递给您的变量 (postsSub)。这就是为什么你不能摧毁它。

改变这个:

   ngOnInit(): void {
    this.postsService.getPosts();
    this.postsService.getPostUpdateListener().subscribe((posts: Post[]) => {
      this.posts = posts;
    });
  }

为此:

  ngOnInit(): void {
    this.postsService.getPosts();
    this.postsSub = this.postsService.getPostUpdateListener().subscribe((posts: Post[]) => {
      this.posts = posts;
    });
  }

应该可以。

问候

相关问题