Javascript 角度布线问题-布线赢得';我不能像往常一样工作
我有一个问题,当我手动键入localhost:4200/create时,它会出现在我希望它出现的页面上,但是当我单击一个链接将我带到那里时,我会收到一个错误,上面写着:Javascript 角度布线问题-布线赢得';我不能像往常一样工作,javascript,angular,Javascript,Angular,我有一个问题,当我手动键入localhost:4200/create时,它会出现在我希望它出现的页面上,但是当我单击一个链接将我带到那里时,我会收到一个错误,上面写着: TypeError: Cannot read property 'unsubscribe' of undefined at PostListComponent.ngOnDestroy 这是我的密码: header.component.html <mat-toolbar color="primary&
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>
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();
}
}
正如错误所说,您正在调用
unsubscribe
对象,该对象在PostListComponent
(postlist.component.ts?)中不存在
在该文件中,找到ngondestory
函数,对于任何this.object$.unsubscribe()
函数,首先测试对象-
if (this.object$ && !this.object$.closed) {
this.object$.unsubscribe()
}
我以
这个.object$
为例-当您从/
导航到/create
时,PostListComponent
中的Ngondestory
抛出错误时,您的变量将被称为不同的
这就是为什么它发生在链接上,而不是当您输入url时。正如您在ngInit中看到的,您没有向变量(postsub)传递任何值。这就是为什么你不能摧毁它 更改此项:
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;
});
}
这应该行得通
关于app.component.htmlShow
PostListComponent.ts中的路由器输出在哪里,我编辑了它谢谢你,我的朋友,但是问题解决了。干杯
ngOnInit(): void {
this.postsService.getPosts();
this.postsSub = this.postsService.getPostUpdateListener().subscribe((posts: Post[]) => {
this.posts = posts;
});
}