Sunday, August 23, 2020

Consuming Observable using Subscribe

To consume an observable by subscribing, we need to call the subscribe() method and capture the result/error objects returned by the observable. In this sample, we will get a list of users using a http.get call which returns an observable.

user.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Subscriber } from 'rxjs';
import { User } from './user';
@Injectable({
  providedIn: 'root'
})
export class UserService {
  url = "https://jsonplaceholder.typicode.com/users";
  constructor(private http: HttpClient) { }
  getUsers(): Observable<User[]> {
                                return this.http.get<User[]>(this.url);
                }
}

app.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService } from '../services/user.service';
import { User } from '../services/user';

@Component({
  selector: 'app-subscribe',
  templateUrl: './subscribe.html'
})
export class SubscribeComponent implements OnInit {
  userList;
  errorMessage: string;
  constructor(private userService: UserService) { }

  ngOnInit() {
    this.userService.getUsers().subscribe(
      data => this.userList = data,
      err => this.errorMessage = err.status + ' - ' + err.statusText
    );
  }
}

app.component.html
<div>
    <ul>
        <li *ngFor="let user of userList" >
        Id: {{user.id}}, Name: {{user.name}}
        </li>
    </ul>
</div>

Output




Search Flipkart Products:
Flipkart.com

No comments: