在 Angular 发送 POST 请求后更新 UI 13
Update UI after sending POST request on Angular 13
我有一个 post 数据的方法和另一个获取数据的方法,每个方法都在其当前按钮和功能上。我想要实现的是在单击发送 Post 时更新 posts 数组。
我的方法是在我创建它们的同一个函数中调用 onFetchPosts,每个函数作为一个单元工作,但是当我试图在创建时调用 fetch 时,它就不会工作
Html File Using Bootstrap 4 and angular template driven forms
``` <div class="container">
<div class="row">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<form #postForm="ngForm" (ngSubmit)="onCreatePost(postForm.value)">
<div class="form-group">
<label for="title">Title</label>
<input
type="text"
class="form-control"
id="title"
required
ngModel
name="title"
/>
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea
class="form-control"
id="content"
required
ngModel
name="content"
></textarea>
</div>
<button
class="btn btn-primary"
type="submit"
[disabled]="!postForm.valid"
>
Send Post
</button>
</form>
</div>
</div>
<hr />
<div class="row">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<button class="btn btn-primary" (click)="onFetchPosts()">
Fetch Posts
</button>
|
<button
class="btn btn-danger"
[disabled]="loadedPosts.length < 1"
(click)="onClearPosts()"
>
Clear Posts
</button>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<p *ngIf="loadedPosts.length < 1 && !isFetching">No posts available!</p>
<ul class="list-group" *ngIf="loadedPosts.length >= 1 && !isFetching">
<li class="list-group-item" *ngFor="let post of loadedPosts">
<h3>{{ post.title }}</h3>
<p>{{ post.content }}</p>
</li>
</ul>
<div class="loading-spinner" *ngIf="isFetching">
<div class="sk-chase">
<div class="sk-chase-dot"></div>
<div class="sk-chase-dot"></div>
<div class="sk-chase-dot"></div>
<div class="sk-chase-dot"></div>
<div class="sk-chase-dot"></div>
<div class="sk-chase-dot"></div>
</div>
</div>
</div>
</div>
</div> ```
Ts File, calling the functions made in the service.ts file
``` import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Post } from './post.model';
import { PostsService } from './posts.service';
@Component({
selector: 'app-post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.scss']
})
export class PostComponent implements OnInit {
loadedPosts: Post[] = [];
isFetching = false;
constructor(private http: HttpClient, private postsService: PostsService) { }
ngOnInit(): void {
this.isFetching = true;
this.postsService.fetchPosts().subscribe(posts => {
this.isFetching = false;
this.loadedPosts = posts;
});
}
// Here I'm trying to call fetchPosts after I create one, but the UI won't get updated
onCreatePost(postData: { title: string; content: string }) {
this.isFetching = true;
this.postsService.createAndStorePost(postData.title, postData.content)
this.postsService.fetchPosts().subscribe(posts => {
this.isFetching = false;
this.loadedPosts = posts;
});
}
onFetchPosts() {
// Send Http request
this.isFetching = true;
this.postsService.fetchPosts().subscribe(posts => {
this.isFetching = false;
this.loadedPosts = posts;
});
}
onClearPosts() {
// Send Http request
this.postsService.deletePosts().subscribe(() => {
this.loadedPosts = [];
});
}
} ```
Service.ts, creating functions to create, fetch and delete posts
``` import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { map } from "rxjs/operators";
import { Post } from "./post.model";
@Injectable({providedIn: 'root'})
export class PostsService {
constructor(private http: HttpClient) {}
createAndStorePost(title: string, content: string) {
const postData: Post = {title: title, content: content};
this.http
.post<{ name: string }>(
'https://to my backend at.firebaseio.com/posts.json',
postData
)
.subscribe(responseData => {
console.log(responseData);
});
}
fetchPosts() {
return this.http
.get<{ [key: string]: Post }>(
'https://to my backend at.firebaseio.com/posts.json'
)
.pipe(
map(responseData => {
const postsArray: Post[] = [];
for (const key in responseData) {
if (responseData.hasOwnProperty(key)) {
postsArray.push({ ...responseData[key], id: key });
}
}
return postsArray;
})
);
}
deletePosts() {
return this.http.delete('https://to my backend at.firebaseio.com/posts.json')
}
} ```
您不需要订阅服务。而是这样做
createAndStorePost(title: string, content: string) {
const postData: Post = { title: title, content: content };
return this.http
.post<{ name: string }>(
'https://to my backend at.firebaseio.com/posts.json',
postData
);
}
然后在你的组件中
onCreatePost(postData: { title: string; content: string }) {
this.isFetching = true;
this.postsService.createAndStorePost(postData.title, postData.content).subscribe(()=>{
this.isFetching = false;
this.onFetchPosts();
});
}
我有一个 post 数据的方法和另一个获取数据的方法,每个方法都在其当前按钮和功能上。我想要实现的是在单击发送 Post 时更新 posts 数组。 我的方法是在我创建它们的同一个函数中调用 onFetchPosts,每个函数作为一个单元工作,但是当我试图在创建时调用 fetch 时,它就不会工作
Html File Using Bootstrap 4 and angular template driven forms
``` <div class="container">
<div class="row">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<form #postForm="ngForm" (ngSubmit)="onCreatePost(postForm.value)">
<div class="form-group">
<label for="title">Title</label>
<input
type="text"
class="form-control"
id="title"
required
ngModel
name="title"
/>
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea
class="form-control"
id="content"
required
ngModel
name="content"
></textarea>
</div>
<button
class="btn btn-primary"
type="submit"
[disabled]="!postForm.valid"
>
Send Post
</button>
</form>
</div>
</div>
<hr />
<div class="row">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<button class="btn btn-primary" (click)="onFetchPosts()">
Fetch Posts
</button>
|
<button
class="btn btn-danger"
[disabled]="loadedPosts.length < 1"
(click)="onClearPosts()"
>
Clear Posts
</button>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<p *ngIf="loadedPosts.length < 1 && !isFetching">No posts available!</p>
<ul class="list-group" *ngIf="loadedPosts.length >= 1 && !isFetching">
<li class="list-group-item" *ngFor="let post of loadedPosts">
<h3>{{ post.title }}</h3>
<p>{{ post.content }}</p>
</li>
</ul>
<div class="loading-spinner" *ngIf="isFetching">
<div class="sk-chase">
<div class="sk-chase-dot"></div>
<div class="sk-chase-dot"></div>
<div class="sk-chase-dot"></div>
<div class="sk-chase-dot"></div>
<div class="sk-chase-dot"></div>
<div class="sk-chase-dot"></div>
</div>
</div>
</div>
</div>
</div> ```
Ts File, calling the functions made in the service.ts file
``` import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Post } from './post.model';
import { PostsService } from './posts.service';
@Component({
selector: 'app-post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.scss']
})
export class PostComponent implements OnInit {
loadedPosts: Post[] = [];
isFetching = false;
constructor(private http: HttpClient, private postsService: PostsService) { }
ngOnInit(): void {
this.isFetching = true;
this.postsService.fetchPosts().subscribe(posts => {
this.isFetching = false;
this.loadedPosts = posts;
});
}
// Here I'm trying to call fetchPosts after I create one, but the UI won't get updated
onCreatePost(postData: { title: string; content: string }) {
this.isFetching = true;
this.postsService.createAndStorePost(postData.title, postData.content)
this.postsService.fetchPosts().subscribe(posts => {
this.isFetching = false;
this.loadedPosts = posts;
});
}
onFetchPosts() {
// Send Http request
this.isFetching = true;
this.postsService.fetchPosts().subscribe(posts => {
this.isFetching = false;
this.loadedPosts = posts;
});
}
onClearPosts() {
// Send Http request
this.postsService.deletePosts().subscribe(() => {
this.loadedPosts = [];
});
}
} ```
Service.ts, creating functions to create, fetch and delete posts
``` import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { map } from "rxjs/operators";
import { Post } from "./post.model";
@Injectable({providedIn: 'root'})
export class PostsService {
constructor(private http: HttpClient) {}
createAndStorePost(title: string, content: string) {
const postData: Post = {title: title, content: content};
this.http
.post<{ name: string }>(
'https://to my backend at.firebaseio.com/posts.json',
postData
)
.subscribe(responseData => {
console.log(responseData);
});
}
fetchPosts() {
return this.http
.get<{ [key: string]: Post }>(
'https://to my backend at.firebaseio.com/posts.json'
)
.pipe(
map(responseData => {
const postsArray: Post[] = [];
for (const key in responseData) {
if (responseData.hasOwnProperty(key)) {
postsArray.push({ ...responseData[key], id: key });
}
}
return postsArray;
})
);
}
deletePosts() {
return this.http.delete('https://to my backend at.firebaseio.com/posts.json')
}
} ```
您不需要订阅服务。而是这样做
createAndStorePost(title: string, content: string) {
const postData: Post = { title: title, content: content };
return this.http
.post<{ name: string }>(
'https://to my backend at.firebaseio.com/posts.json',
postData
);
}
然后在你的组件中
onCreatePost(postData: { title: string; content: string }) {
this.isFetching = true;
this.postsService.createAndStorePost(postData.title, postData.content).subscribe(()=>{
this.isFetching = false;
this.onFetchPosts();
});
}