Heru S
Heru S

Reputation: 1323

How can we add another subscribe action in the http observable in angularjs2?

I am new to Angular2. I have a LoginComponent which takes in an action called submitLogin from a submit button. When clicked, it will send the username and password (via the UserService) to the API server (with the help of UtilService). If the server responds OK, it will return with a token, and we would save it locally and redirect it.

So far, I have managed to send the username and password and save the token. But, I am confused on how we can add another action in the LoginComponent so that we can redirect the user. (I have added a comment in the login.component.ts below to clarify what I would like to do).

Feel free to let me know if I am not making myself clear.

Here are the codes that I have:

login.component.ts has the following:

import {Component, OnInit} from 'angular2/core';
import {NgForm}    from 'angular2/common';
import {UserService} from '../services/user.service';

@Component({
  selector: 'login',
  templateUrl: './components/login/login.component.html',
  styleUrls: ['./components/login/login.component.css']
})
export class LoginComponent implements OnInit {
  public username: string;
  public password: string;
  public loginResult: string;

  constructor(private _userService: UserService) {}
  ngOnInit() { }
  submitLogin() {
    var p = this._userService.login(this.username, this.password);
    // HOW TO: 
    // I know p is an observable. But, is it possible to add a condition as follow:
    // if p is success, then redirect
    // if p failed, then return
  }
}

user.service.ts:

import {Injectable} from 'angular2/core';
import {UtilsService} from './utils.service';

@Injectable()

export class UserService {
  constructor(private _utils: UtilsService) { }

  login(username: string, password: string) {
    var request = {
      method: 'POST',
      headers: { 'Authorization': 'Basic ' + btoa(username + ':' + password) },
      url: '/auth/',
      data: null
    };

    return this._utils.api(request).subscribe(
      data => this.setAccessToken(data.json().access_token),
      err => console.log(err)
    );
    var promise = this._utils.api(request);
    promise.then((response) => {
      this.setAccessToken(response.token);
    });
  }

}

utils.service.ts:

import {Injectable} from 'angular2/core';
import {Http, Headers} from 'angular2/http';

@Injectable()

export class UtilsService {
  private apiUrl: string;
  constructor(public http: Http) {
    this.apiUrl = '/api/1';
  }
  api(request: any) {
    var headers = new Headers();
    var url = this.apiUrl + request.url;

    if(request.headers) {
      for(var key in request.headers) {
        headers.append(key, request.headers[key]);
      }
    }

    if(!request.type || request.type === 'GET') {
      return this.http.get(url, { headers: headers });
    }

    if(request.type === 'POST') {
      return this.http.post(url, request.data, { headers: headers });
    }

    if(request.type === 'PUT') {
      return this.http.put(url, request.data, { headers: headers });
    }

    if(request.type === 'DELETE') {
      return this.http.delete(url, { headers: headers });
    }
    return false;

  }
}

Upvotes: 0

Views: 7131

Answers (1)

Sasxa
Sasxa

Reputation: 41264

If you make your UserService.login() return observable (not subscriber, as it does now) you can subscribe to it in LoginComponent

export class UserService {
  login(username: string, password: string) {

    return this._utils.api(request)
      .map(response => response.json())
    );
  }
}

export class LoginComponent implements OnInit {
  submitLogin() {
    var p = this._userService
      .login(this.username, this.password)
      .subscribe(

        // success
        (data) => { 
          this._userService.setAccessToken(data.access_token); 
          // redirect here...
        }, 

        // error
        (error) => {}, 

        // completed
        () => {}  
      )
  }
}

Upvotes: 9

Related Questions