Angular 6在POST后未更新视图。
创始人
2024-10-16 10:01:13
0

问题描述: 在使用Angular 6进行POST请求后,视图没有更新。

解决方法:

  1. 确保在POST请求后更新视图的代码已经正确实现。在组件中,可以使用Observables来监听HTTP请求的响应,然后在响应返回后更新视图。示例代码如下:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-my-component',
  template: `
    

Posts

  • {{ post.title }}
` }) export class MyComponent { posts: any[]; constructor(private http: HttpClient) {} ngOnInit() { this.getPosts(); } getPosts() { this.http.get('https://jsonplaceholder.typicode.com/posts') .subscribe(posts => { this.posts = posts; }); } createPost() { const postData = { title: 'New Post' }; this.http.post('https://jsonplaceholder.typicode.com/posts', postData) .subscribe(() => { this.getPosts(); // 更新视图 }); } }

在这个例子中,我们首先通过GET请求获取了一些post数据,然后在视图中展示它们。当点击“Create Post”按钮时,会发送一个POST请求来创建新的post。在POST请求的回调函数中,我们再次调用了getPosts()方法来更新视图。

  1. 确保在服务端成功创建了新的post。可以使用开发者工具或其他网络调试工具来检查POST请求的返回结果,确保服务端正确处理了请求,并返回了正确的响应。

  2. 如果服务端成功创建了新的post,但视图仍然没有更新,那么可能是由于Angular的变更检测机制导致的。可以尝试在代码中手动触发变更检测。示例代码如下:

import { Component, ChangeDetectorRef } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-my-component',
  template: `
    

Posts

  • {{ post.title }}
` }) export class MyComponent { posts: any[]; constructor(private http: HttpClient, private cdr: ChangeDetectorRef) {} ngOnInit() { this.getPosts(); } getPosts() { this.http.get('https://jsonplaceholder.typicode.com/posts') .subscribe(posts => { this.posts = posts; this.cdr.detectChanges(); // 手动触发变更检测 }); } createPost() { const postData = { title: 'New Post' }; this.http.post('https://jsonplaceholder.typicode.com/posts', postData) .subscribe(() => { this.getPosts(); }); } }

在这个例子中,我们注入了ChangeDetectorRef服务,并在getPosts()方法中调用detectChanges()方法来手动触发变更检测。

通过以上方法,你应该能够解决Angular 6在POST后未更新视图的问题。

相关内容

热门资讯

解谜透视!wepoker辅助是... 解谜透视!wepoker辅助是真的假的,微乐小程序挂哪里,机巧教程(有挂解惑)-哔哩哔哩1、在wep...
揭幕透视!hhpoker免费透... 揭幕透视!hhpoker免费透视脚本,微乐自建房辅助工具2025在哪,窍要教程(有挂技巧)-哔哩哔哩...
关于透视!agpoker辅助,... 关于透视!agpoker辅助,微乐智能辅助软件是真的吗,绝活儿教程(发现有挂)-哔哩哔哩1、每一步都...
关于透视!智星德州插件怎么下载... 关于透视!智星德州插件怎么下载,微信小程序微乐辅助器免费版,模板教程(有挂透明挂)-哔哩哔哩1、智星...
关于透视!来玩德州破解器,微信... 关于透视!来玩德州破解器,微信小程序微乐辅助器免费版v2.0免费,手筋教程(有挂透明挂)-哔哩哔哩1...
教你透视!德州透视脚本,微乐小... 教你透视!德州透视脚本,微乐小程序挂哪里有,模块教程(有挂教程)-哔哩哔哩1、实时德州透视脚本透视辅...
揭幕透视!aa poker透视... 揭幕透视!aa poker透视软件,微乐小程序辅助教程,讲义教程(有挂秘诀)-哔哩哔哩1、很好的工具...
详细透视!pokemmo脚本最... 详细透视!pokemmo脚本最新版,微乐自建房辅助可信吗,指南教程(了解有挂)-哔哩哔哩1、首先打开...
必备透视!wepoker能不能... 必备透视!wepoker能不能透视,微乐小程序破解版修改器,模块教程(有挂教学)-哔哩哔哩1、许多玩...
教你透视!hhpoker辅助挂... 教你透视!hhpoker辅助挂下载,微信小程序 微乐陕西挖坑 外挂,教程书教程(有挂技术)-哔哩哔哩...