我遇到了一个我不清楚的错误。
我可以看到要编辑的数据,但每次都会出现这样的错误。
我试图捕获错误,但我没有得到它来自哪里:
每个 console.log 都可以正常工作。
我认为问题出在第一次加载时数据为空的地方。
只有当我尝试显示第二个 ngFor
时,才会出现这种情况。因为如果我只让第一个比它工作得很好但没有显示那么 arrays of comments the second *ngFor
.
RROR TypeError: Cannot read property '1' of null
at Object.eval [as updateDirectives] (PostsListComponent.html:20)
at Object.debugUpdateDirectives [as updateDirectives]
我得到的数据是这样的。
<tr *ngFor="let post of posts$ | async; trackBy:trackByFunction">
<td class="title">{{post.title}}</td>
<td class="dateTime">{{post.body}}</td>
<div *ngFor="let comment of (groupedComments$ | async)[post.id]; trackBy:trackByFunction">
<div>
<td *ngIf="!isEditable(comment)" class="comment">{{comment.name}}</td>
<textarea class="comment" *ngIf="isEditable(comment)" [(ngModel)]="editableComment.name"></textarea>
<td *ngIf="!isEditable(comment)"class="comment">{{comment?.body}}</td>
<textarea class="comment" *ngIf="isEditable(comment)" [(ngModel)]="editableComment.body"></textarea>
<td class="comment" *ngIf="comment.email === 'Just@do.it' && comment.body.length < 200">
{{comment.email}}
<button *ngIf="!isEditable(comment)" (click)="deleteComment(comment.id)" class="btn btn-danger">Delete</button>
<button *ngIf="!isEditable(comment)" (click)="editComment(comment)" class="btn btn-info" style="margin-left: 10px">Edit</button>
<button *ngIf="isEditable(comment)" (click)="update(comment)" class="btn btn-info" style="margin-left: 10px">Update</button>
<button *ngIf="isEditable(comment)" (click)="cancel()" class="btn btn-danger" style="margin-left: 10px">Cancel</button>
</td>
</div>
</div>
</tr>
TS
文件。
posts$: Observable<Post[]>;
comments$: Observable<Comment[]>;
groupedComments$: Observable<CommentGroup>;
editableComment = emptyComment();
constructor(private postsService: PostService,
private commentsService: CommentService,
private confirmationDialogService: ConfirmationDialogService) {
this.getAllData();
}
ngOnInit() {
}
getAllData() {
this.posts$ = this.postsService.getPostsList();
this.comments$ = this.commentsService.getCommentsList();
this.groupedComments$ = this.comments$.pipe(
map(comments => lodash.groupBy(comments, 'postId')),
);
}
这就是我的服务。
export class PostService {
private baseUrl = 'http://localhost:3000/posts';
constructor(private http: HttpClient) { }
getPostsList(): Observable<any> {
return this.http.get(`${this.baseUrl}`);
}
}
export class CommentService {
private baseUrl = 'http://localhost:3000/comments';
constructor(private http: HttpClient) { }
getComment(id: number): Observable<any> {
return this.http.get(`${this.baseUrl}/${id}`);
}
getCommentsList(): Observable<any> {
return this.http.get(`${this.baseUrl}`).pipe(catchError(this.errorHandler));
}
}
最佳答案
groupedComments$ | async
是 null
在接收http响应之前,这就是原因。
关于javascript - 错误 TypeError : Cannot read property '1' of null at Object. eval [作为 updateDirectives],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58798307/