gpt4 book ai didi

javascript - Angular 路由问题 - 路由无法正常工作

转载 作者:行者123 更新时间:2023-12-02 02:09:34 24 4
gpt4 key购买 nike

我有一个问题,当我手动输入 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>

应用程序路由.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();
}
}

最佳答案

如错误所述,您正在对 PostListComponent 中不存在的对象调用 unsubscribe(poSTList.component.ts?)

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

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

我以 this.object$ 为例——你的变量将被称为不同的东西

关于javascript - Angular 路由问题 - 路由无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67888035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com