1

I am requesting data from API through service.ts. i want server response into my component's local variable for further manipulation.i have tried with subscribe method, map method, Observable method..but all are giving sort of error..whose solution is not available on Internet.

here is hierarchy...

\auth
-- html,ts,css,spec.ts
-- auth-service.ts

here is authcomponent.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { AuthService } from './auth.service';
import { Router } from '@angular/router';
import {LocalStorage, SessionStorage} from "angular-localstorage/";
import { error } from 'selenium-webdriver';

@Component({
  selector: 'app-auth',
  templateUrl: './auth.component.html',
  styleUrls: ['./auth.component.css'],
  providers:[AuthService]
})
export class AuthComponent implements OnInit {
  registerForm: FormGroup;
  loginForm : FormGroup;
  isLogin = true;
  result : any;
  constructor(private authService:AuthService, private router: Router ) {

   }
   this.loginForm = new FormGroup ({
  username: new FormControl(),
  password: new FormControl()
  })

  onLogin(){
    this.authService.login(this.loginForm.value)
    .map(  
        res =>
         {
          this.result = res;
      },error => {
        console.log(error);
      }
    )
  }

}

auth-service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';;
import { LocalStorage, SessionStorage } from "angular-localstorage/";
import { Configuration } from '../config'
import 'rxjs/add/operator/map';
import { Router } from '@angular/router';

declare var $: any;



@Injectable()
export class AuthService {

  constructor(private http:HttpClient, private config: Configuration, private router:Router) { }
  api_url = this.config.ServerWithApiUrl;

  login(newLogin){
    return this.http.post( this.api_url+'login', newLogin);
  }
}
AlpeshVasani
  • 227
  • 4
  • 15

3 Answers3

1

Very close to a duplicate...

To fire off a http-request you need to subscribe like has been suggested since it's a cold observable.

So when you now have attempted below after that suggestion:

onLogin() {
  this.authService.login(this.loginForm.value)
    .subscribe(res => {
      this.result = res;
    },
    error => {
      console.log(error);
    });
    console.log(this.result);   // returns undefined..
}

The console log will be undefined as this is asynchronous and it takes a while for the response to come, while waiting for the response Angular will execute any synchronous operations, therefore the console log is executed before response has arrived. Read more about this here: How do I return the response from an Observable/http/async call in angular2?

So move the console log inside the callback and you will get the desired result:

.subscribe(res => {
  this.result = res;
  console.log(this.result) // will not be 'undefined' anymore!
},
AT82
  • 71,416
  • 24
  • 140
  • 167
0

you need to use subscribe into component instead of map

onLogin(){
    this.authService.login(this.loginForm.value).subscribe(  
      (res: any) => {
          this.result = res;
      },error => {
        console.log(error);
      }
    )
  }

you need to import in service this line

import {Observable} from 'rxjs/Observable';

Service function should be like.

  login(newLogin)Observable<any>{
        return this.http.post(this.api_url+'login', newLogin).map(
                (res: Response) => {
                    return res.json() ;
                }).catch(
                (error: Response) => {
                    return Observable.throw(error.json());
                });
      }
Shailesh Ladumor
  • 7,052
  • 5
  • 42
  • 55
  • What do you mean by resource type?? – AlpeshVasani Dec 25 '17 at 11:44
  • I manage to solve other issues and error but still after onLogin function console.log(this.result); gives me undefined – AlpeshVasani Dec 25 '17 at 17:45
  • console in service and check and debug also – Shailesh Ladumor Dec 26 '17 at 04:09
  • error TypeError: Cannot read property 'length' of null at HttpHeaders.applyUpdate (http.js:322) at eval (http.js:269) at Array.forEach () at HttpHeaders.init (http.js:269) at HttpHeaders.forEach (http.js:368) at Observable.eval [as _subscribe] (http.js:2172) at Observable._trySubscribe (Observable.js:172) at Observable.subscribe (Observable.js:160) at subscribeToResult (subscribeToResult.js:23) at MergeMapSubscriber._innerSub (mergeMap.js:138) – AlpeshVasani Dec 26 '17 at 04:24
  • console newLogin and check value and also check url – Shailesh Ladumor Dec 26 '17 at 04:34
  • same issue https://stackoverflow.com/questions/47322257/typeerror-cannot-read-property-length-of-null-at-httpheaders-applyupdate-an – Shailesh Ladumor Dec 26 '17 at 04:34
  • Yes..i tried to find solution over your suggestions already..but no solution is provided there... – AlpeshVasani Dec 26 '17 at 04:43
0

First in your service.ts file import

import { Observable } from 'rxjs/Observable';
import { Http, Response } from '@angular/http';

And in your method

login(newLogin): Observable<any> {
return this.http.post(this.api_url + 'login', JSON.stringify(newLogin)).map((response: Response) => {
return response.json();
});
}

And in your component method you have subscribe to get the response and assign to your variable.

onLogin() {
this.authService.login(this.loginForm.value).subscribe(res => {
this.result = res;
},
error => {
console.log(error);
});
}

Hope it helps.

Kirubel
  • 1,461
  • 1
  • 14
  • 33