typescript Angular 6 将项目添加到 Observable 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53260269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:42:46  来源:igfitidea点击:

Angular 6 add items into Observable

angulartypescriptobservable

提问by Francis Rubia

I'm new to Angular 6 and i'm having trouble on how i can add objects into observable in a service.

我是 Angular 6 的新手,我在如何将对象添加到服务中的 observable 方面遇到了麻烦。

i have this observable

我有这个可观察的

 getContacts(){
  return this.contact = 
  this.http.get('https://jsonplaceholder.typicode.com/users');
 }

and i need to add an item into that observable via another function

我需要通过另一个函数将一个项目添加到该 observable 中

addContact(item){
 //observable insertion goes here.
}

Here is my full service code

这是我的完整服务代码

export class ContactService {

contact;
details;

constructor(private http: HttpClient) {}

getContacts(){
 return this.contact = 
 this.http.get('https://jsonplaceholder.typicode.com/users');
}

addContact(contactName: string, contactPhone: string){

}

}

回答by Vahid

If this.contactsis an Observable of list of objects (contacts: Observable<Items[]>) and you want to make some changes to that list, you can simply use map:

如果this.contacts是对象列表 ( contacts: Observable<Items[]>)的 Observable并且您想对该列表进行一些更改,则可以简单地使用map

import { map } from 'rxjs/operators';

this.contacts.pipe(map(usersList => {
  usersList.push(newItem);
  return usersList;
}));

But if you want to make another request to the server and merge these lists, you can use forkJoin:

但是如果你想向服务器发出另一个请求并合并这些列表,你可以使用forkJoin

import { forkJoin } from 'rxjs';

forkJoin(
  this.contacts,
  this.http.get('https://jsonplaceholder.typicode.com/other_users');
).pipe(
  map(data => {
    const [currentResult, pastResult] = data;
    // ...
  }
));

Update

更新

Based on your comment for more details, you don't need to do anything with observables. What you need is something like this:

根据您对更多详细信息的评论,您不需要对 observable 做任何事情。你需要的是这样的:

In your contacts.service.ts:

在您的contacts.service.ts

getContacts(){
  return this.http.get('https://jsonplaceholder.typicode.com/users');
}

In your contacts.component.ts`:

在你的contacts.component.ts`中:

contacts: any[] = [];
ngOnInit() {
  this.contactsService.getContacts().subscribe(data => {
    this.contacts = data;
  });
}

addContact(item) {
  this.contacts.push(item);
}

But if you really want to have your contacts list as an Observable, you should use Subject.

但是如果你真的想把你的联系人列表作为一个 Observable,你应该使用Subject.

In your contacts.service.ts:

在您的contacts.service.ts

$contactsChange = new Subject<any>();
private contactsList = [];
getContacts(){
  return this.http.get('https://jsonplaceholder.typicode.com/users').pipe(map(data => {
    this.contactsList = data;
    this.$contactsChange.next(this.contactsList);
  }));
}

addContact(item) {
  this.contactsList.push(item);
  this.$contactsChange.next(this.contactsList);
}

In your contacts.component.ts`:

在你的contacts.component.ts`中:

contacts: any[] = [];
ngOnInit() {
  this.contactsService.getContacts().subscribe(data => {this.contacts = data});
  this.contactsService.$contactsChange.subscribe(data => {this.contacts = data});
}

回答by Hassan

Working With Observable

使用 Observable



In Your Service

为您服务

private contactInsertedSubject = new Subject<Contact>();
contactInsertedActions$ = this.contactInsertedSubject.asObservable();

 public contacts$ = this.http.get<Contact[]>(this.contactsUrl)
            .pipe(
              // tap(data => console.log('Contacts: ', JSON.stringify(data))),
              catchError(this.handleError)
            );
public contactsWithAdd$ = merge(this.contacts$, this.contactInsertedActions$)
                        .pipe(
                          scan((acc: Product[], value: Product) => [...acc, value])
                        );
addContact(newContact?: Contact) {
   this.contactInsertedSubject.next(newContact);
}


Your Contact Component Class

您的联系人组件类

contacts$ = this.contactService.contactsWithAdd$;
onAdd(): void {
   this.contactService.addProduct();
}

when this add method will call the subject in service will emit the value and merge observable has two input observable if any one will emit value so this will call automatically and then in pipe map operator will do the insertion job and contactWithAdd observable will have updated list.

当此 add 方法将调用服务中的主题时将发出值并且合并 observable 有两个输入 observable 如果任何一个将发出值所以这将自动调用然后在管道映射操作员将执行插入工作并且 contactWithAdd observable 将有更新的列表.

回答by ararb78

The addContact () method is where you subscribe to the observable getContacts():

addContact() 方法是您订阅可观察的 getContacts() 的地方:

getContacts(): Observable<any> {   
    return this.contact = 
    this.http.get('https://jsonplaceholder.typicode.com/users');
}

At the time of subscription is when the call is triggered:

订阅时是触发调用时:

addContact(){
    let cont: Observable<contactModel>;
    cont = this.getContacts();
    prueba.finally(() => {
       console.log('Finally callback')
    })
    cont.subscribe(res => {
        console.log('at the time of subscription is when the call is triggered')
        let resp: contactModel[];
        resp = res.json() as contactModel[];  
    });


}