首页 > 解决方案 > Angular 6 如何获取从组件到服务的方法调用状态?

问题描述

我想在我的组件中获取方法的状态。

SendEmail.component.ts

sendEmail(form: NgForm) {

this.contractService.sendEmail(form.value.FullName, form.value.content,  form.value.Email);

// if successfull then show alert///

console.log(value);
form.resetForm(); }

我的服务.ts

sendEmail(FullName: string, content: string, Email: string) {
const Contact: Contacts = { _id: null, FullName: FullName, Content: content, Email: Email };
this.http
  .post<{ message: string; contact: string }>('http://localhost:3000/api/contacts', Contact)
  .pipe(
    map( (data: any) => {
      const result: any = [];
      data.map(item => {
        item = JSON.parse('Success');
      });
      return result;
    })
  )
  .subscribe(responseData => {
      this.contacts.push(Contact);
      this.contactsUpdated.next([...this.contacts]);
    });
}

我想在 sendEmail 方法内部成功或错误时获取组件中的状态。谢谢大家,加油

标签: angulartypescript

解决方案


好吧,您可以从sendEmail方法中发送它。所以在那里而不是在subscribe块中写你的逻辑,只需将它写在map运算符中并sucess从那里返回:

export interface Message { 
  message: string; 
  contact: string; 
}

...    

sendEmail(FullName: string, content: string, Email: string) {

  const Contact: Contacts = {
    _id: null,
    FullName,
    Content: content,
    Email
  };

  return this.http.post<Message>('http://localhost:3000/api/contacts', Contact)
    .pipe(
      map((data: any) => {
        const result: any = [];
        data.map(item => {
          item = JSON.parse('Success');
          // this looks shady as you haven't returned anything from here
        });

        this.contacts.push(Contact); // Not sure what's Contact here
        this.contactsUpdated.next([...this.contacts]); // Not sure what's contacts here.

        return 'success';
      })
    );
}

然后,您可以返回subscribe任何sendEmail方法返回,这基本上是Observable<string>

sendEmail(form: NgForm) {

  const { FullName, content, Email } = form.value;

  this.contractService.sendEmail(FullName, content, Email)
    .subscribe(res => {
      if(res === 'success') alert('Got the response');
      console.log(value);
      form.resetForm();
    })
}

注意:请务必仔细阅读评论。您在运算符中的逻辑map看起来是错误的。不太清楚你在里面做什么。


推荐阅读