简体   繁体   中英

Angular 6 How to get status of method call from Component to Service?

I want to get status of method in my component.

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(); }

My Services.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]);
    });
}

I want to get status in component when success or error in inside sendEmail method. Thanks all, Cheer

Well, you could send that from the sendEmail method. So in there instead of writing your logic in the subscribe block, just write it in the map operator and just return sucess from there:

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';
      })
    );
}

You can then subscribe to whatever the sendEmail method returns, which would essentially be an 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();
    })
}

NOTE: Please make sure to go through the comments. Your logic in the map operator looks wrong. Not really sure what you're doing in there.

Add { observe: 'response' } at the last part of your HTTP POST Call

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

   this.http
     .post<ContactBody>('http://localhost:3000/api/contacts', Contact, { observe: 'response' })    // Add observe: 'response'
     .pipe(...)
     .subscribe(...);
}

The "{ observe: <any> }" value specifies what we are currently interested in observing and therefore also changes here the response type of our HTTP request. In our case, we observe the response {observe: 'response'}


Had created a StackBlitz Demo for your reference - Check the console for the result.

1.) Plain HTTP Call with Plain Data Response

this.http
  .post(url, data)
  .subscribe(data => console.log(data));

川

2.) HTTP Call with { observe: 'response'} and Full HTTP Response details

 this.http
  .post(url, data, { observe: 'response' })
  .subscribe(data => console.log(data));

守

Please try below code.

True for success and False for failure.

sendEmail(FullName: string, content: string, Email: string):boolean {
let status:boolean =false;
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]);
      status=true;
    });
return status;
}

You are subscribing it in Service. Instead of doing this, you can return the Observable from Service and In the Component you will subscribe it to get the success or error status.

You should use a dedicated service which will be responsible to do a server call and return the response as Observable so that you can do whatever you want in the Component.

I think it is worthy to give some time on official documentation of Angular. Here is the link . It will help to get a clear understanding about how it is done and what is the good approach to do http call in Angular.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM