Piyush Patel
Piyush Patel

Reputation: 1751

How to get data from server in Angular front end

I am trying a simple login/signup form. I want to show login successful message on the client side Angular app when the user was successful on the server side. From the serverside I am sending

res.json( {
  title: 'Success',
  message: "Success!",
  token: token // using jsonwebtoken
});

I am using userService for authentication. This is authentication method.

authenticateUser(user: User): Observable<any>{
    const submittedUser = JSON.stringify(user);
    const headers = new Headers({ 'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    return this.http.post( baseURL + 'user/signin', submittedUser, options)
      .map(response => this.processHttpmsgService.extractData(response))
      .catch(error => Observable.throw(error));
  }

This is using processHttpmsgService which simply converts response object into json. Here is extractData method.

public extractData(res: Response) {
    let body = res.json();
    console.log(body);  // server sent data available here.
    return body;
  }

Now, server sent data object is availble upto extractData() method. But when I go back into onSubmit() method in signin component. There, on subscription, the data is not available. This is my onSubmit() method.

onSubmit() {
    this.user = this.signinForm.value;
    this.userService.authenticateUser(this.user) 
      .subscribe(data => {
        this.data = data;
        console.log(data);   // undefined
        console.log(this.data);  // undefined
        localStorage.setItem('token', this.data.token);
        this.router.navigateByUrl('/');
      },
                error => {console.error(error); this.router.navigateByUrl('/signin');});
    this.signinForm.reset();

  }

I don't know why the data is becoming undefined in onSubmit method. I hope I am making right method calls.

Upvotes: 0

Views: 1504

Answers (3)

Amit
Amit

Reputation: 1560

Try with removing map(), it should be worked:

return this.http.post( baseURL + 'user/signin', submittedUser, options)
          .catch(error => Observable.throw(error));

Upvotes: 0

jitender
jitender

Reputation: 10429

try changing

return this.http.post( baseURL + 'user/signin', submittedUser, options)
      .map(response => this.processHttpmsgService.extractData(response))
      .catch(error => Observable.throw(error));

to

return this.http.post( baseURL + 'user/signin', submittedUser, options)
      .map(response => response.json())
      .catch(error => Observable.throw(error));

Upvotes: 0

Marcelo Rodrigues
Marcelo Rodrigues

Reputation: 46

String in Json should be in double quote. Try to change the title:

{
    title: "Success",
    message: "Success!",
    token: token // using jsonwebtoken
 }

http://www.json.org/

Upvotes: 1

Related Questions