Angular可观察数组,由http请求和手动添加的数据填充 [英] Angular observable array, populated by an http request and manually added data
问题描述
我正在努力探索Angular 6中的可观察性,但是除了AngularJS以外,我是新事物,现在正处于严重的挣扎中.我想我已经遍历了所有可以在这里找到和搜索的教程,因此希望我不会错过任何内容,但是很乐意接受友好的指导...
I'm trying to get my head around observables in Angular 6, but I'm new to anything more recent than AngularJS and seriously struggling right now. I think I've gone through every tutorial I can find and searched extensively here, so hopefully I'm not missing anything, but happy to take friendly pointers...
我想做的是这样:
- 获取对后端API的请求,返回一个项的JSON数组,并将该数组作为数据列表显示在组件中
- 允许第二个组件将新的商品发布到后端,并将该商品添加到上面的商品列表中
- GET request to a backend API, returns a JSON array of items, and display that array in a component as a data list
- Allow a second component to POST new items to the backend, and also add that item to the list of items above
我猜我正在描述一个可观察的对象,因为#1必须是异步的,但是我看到的所有示例似乎都只处理两个步骤之一,而不是两个都一起.我想念什么?
I'm guessing I'm describing an observable, because #1 needs to be asynchronous, but all the examples I've seen seem to only deal with one of the two steps, not both together. What am I missing?
推荐答案
@ 1:对后端API的GET请求,返回JSON项数组,并将该数组作为数据列表显示在组件中
@1: GET request to a backend API, returns a JSON array of items, and display that array in a component as a data list
我们将此称为ComponentA:
let's call this one ComponentA:
export class ComponentA {
arrayOfItems:Type[];
constructor(private http:HttpClient) {}
getDataFromAPI():Observable<Type[]> {
this.http.get<Type[]>('api-get-url')
.subscribe(
(items) => {
//print them if you want;console.log('response from the api', items);
this.arrayOfItems = items;
}
)
}
}
@ 2.1:允许第二个组件将新项目发布到后端(故意省略了一部分问题)
@2.1: Allow a second component to POST new items to the backend (omitted a part of the question on purpose)
export class ComponentB {
// let's assume this array is already populated
// via you 2-way bindings or whatever means
newItems:Type[];
constructor(private http:HttpClient) {}
postDataToAPI():Observable<any> {
this.http.post('api-post-url', this.newItem)
.subscribe(
response => console.log('response from the api', response);
)
}
}
@ 2.2,并将该项目添加到上面的项目列表中
@2.2 and also add that item to the list of items above
一切都非常简单,但是现在您必须停下来思考:我有一些这里"和一些那里".我如何...将它们连接起来?哈!连接!因此,我需要某种机制来连接这两个组件.你做什么工作?您使用服务!但是一项旨在存储共享数据集的服务.您可以将其称为DataStoreService.
Everything ^ was straightforward, but now you gotta stop and think: I have something 'here' and something 'there'. How can I ... connect them? Ha! Connect! So I need some sort of mechanism to connect the 2 components. What do you do? You use a service! But a service whose purpose is to store a shared data set. You can call it DataStoreService.
让我们(重新)编写一些代码:
Let's (re)write some code:
@Injectable()
export class DataStoreService() {
items:Type[] = [];
constructor(private http:HttpClient) {}
getDataFromTheAPI():Observable<Type[]> {
this.http.get<Type[]>('api-get-url')
.subscribe(items => this.items = items)
}
postDataToTheAPI(itemToAdd:Type):Observable<any> {
this.http.post('api-post-url', itemsToAdd)
.subscribe(
(response) => {
// check if all is good, and add it to the 'items' array
addItem(itemToAdd);
}
}
)
}
getItems() {
return this.items;
}
addItem(item:Type) {
this.items.push(item);
}
}
现在,您的组件A更改为:
Now, your Component A changes to:
export class ComponentA implements OnInit{
constructor(private dataStoreService: DataStoreService) {}
ngOnInit(): void {
this.dataStoreService.getDataFromTheAPI();
// ^ will request the data from the API and store it
// inside the service
}
// and here you get a reference to that data
get itemsReferenceFromService() {
return this.jobsStoreService.getJobsArray();
}
}
和ComponentB一起:
And ComponentB to:
export class ComponentB {
newItem:Type;
constructor(private dataStoreService: DataStoreService) {}
// when you do this, if successful, addItem method
// will also be called that will 'and also add that item to the list of items above'; as componentA only has a reference to the data in
// the service, the new item will be displayed it it
this.dataStoreService.postDataToTheAPI(newItem);
}
希望这能回答您的问题.如果您还有其他疑问,请大声说出来.像url这样的信息被省略了.
Hope this answers your question. If you have any other doubts, say it loud. Info like urls were omitted.
进一步的改进是拥有另一种仅 处理API调用的服务,并保持DataService 干净仅用于存储目的.这样可以简化测试.
A further improvement is to have another service that only handles the API calls, and keep the DataService clean just for storing purposes. That will ease testing.
请注意,直到最终用户刷新页面后,任何服务/组件的使用寿命才能延长.所描述的服务不是持久性机制.
Be aware that the lifespan of any Service/Component in angular is up untill the end user refreshed the page. The service described is not a persistence mechanism.
这篇关于Angular可观察数组,由http请求和手动添加的数据填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!