0
@WebServlet("/findPerson")
public class FindPerson extends HttpServlet {
    // ... doGet implementation

    @Override
    protected void doPost( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException {

        // data to send to the client
        String name = "John White";
        int age = 54;



        // Adding attributes to the request
        request.setAttribute( "personName", name );
        request.setAttribute( "personAge", age );

        }
    }
}

How do I get the value of these attributes "personName" and "personAge" in angular after calling

return  this.http.post('http://localhost:8080/findPerson',"");
Ashim
  • 877
  • 2
  • 12
  • 22

1 Answers1

0

this.http.post() returns an observable. You need to subscribe to it to obtain the response

Service

findPerson(): Observable<any> {
  return this.http.post('http://localhost:8080/findPerson',"");
}

Component

name: any;
age: any;

this.someService.findPerson().subscribe(
  res => {
    this.name = res['personName'];
    this.age = res['personAge'];
    console.log(this.name); // <-- correct
    console.log(this.age); // <-- correct
  },
  error => {
    // always good practice to handle HTTP errors
  }

  console.log(this.name); // <-- wrong - would print `undefined`
  console.log(this.age); // <-- wrong - would print `undefined`
);

Most important thing to note is that the call is asynchronous. So any statements that directly depend on the response should be inside the subscription. Or in other words, you need to subscribe where the response is required.

You could learn more about asynchronous data here.

ruth
  • 29,535
  • 4
  • 30
  • 57
  • [Error] ERROR – TypeError: null is not an object (evaluating 'res['status']') — login.component.ts:55 TypeError: null is not an object (evaluating 'res['status']') — login.component.ts:55(anonymous function) — login.component.ts:55__tryOrUnsub — .... – Ashim Oct 14 '20 at 08:32
  • @Ashim: It appears the server isn't sending anything back. I'm not familiar with HttpServlet, but I don't see something being returned. Eg. I don't see the MIME type of the response. Please check [here](https://stackoverflow.com/q/9645647/6513921) on how to return an object in JSON from Servlet. – ruth Oct 14 '20 at 08:39