Skip to main content

Subscribe() in Angular

Subscribe is a method that comes from rxjs library which Angular is using behind the scene.
If you can imagine yourself when subscribing to a news letter and after the subscribing, every time that there is a new news letter, they will send it to your home

All the AJAX calls in Angular is using this library behind the scene and in order to use any of them, you've got to use the method name, e.g get, and then call subscribe on it, because get returns and Observable.

Also, when you're doing this <button click="dosomething()"></button>  Angular is using Observable's behind the scene and subscribes you to that source of thing, which in this case is a click event.

Here subscribe is used along with observable to get the latest updates of the observable data.

Angular Service with Observable : In the below code we are creating a Observable as Observable's are usually denoted as suffix $, in the below code userTextObservable$


import { Injectable } from '@angular/core';
import { BehaviorSubject } from '../../../node_modules/rxjs';

@Injectable({
  providedIn: 'root'
})
export class PreviewService {

private _userTextSubject = new BehaviorSubject(null);
userTextObservable$ = this._userTextSubject.asObservable();

onUserEneters(userText :string){
  this._userTextSubject.next(userText);
}
}


Subscribing a Observable :
                Here we are subscribing to the above Observable and used to get the updated information from observable.

import { Component, OnInit } from '@angular/core';
import {PreviewService} from '../services/preview-service.service';
@Component({
  selector: 'second-component',
  templateUrl: './second-component.component.html',
  styleUrls: ['./second-component.component.css']
})
export class SecondComponentComponent implements OnInit {

  public previewText:string;
  constructor(private previewService :PreviewService) { }

  ngOnInit() {
    this.previewService.userTextObservable$.subscribe(x=>this.previewText=x);
  }
}

That's it !!

Comments

  1. Your articles are very useful. They give me a lot of information. I may learn knowledge from them. I can't help reading your posts. It's very kind of you to share your insight. I really like your pieces of writing. They help me so much. Thanks a million. I am waiting new posts. Đăng ký VD300 VinPhone, Đăng ký MAXSV2 VinaPhone, Đăng ký 3G VinaPhone 1 ngày

    ReplyDelete
  2. I have a fancy for your posts. They are so great and useful. You deserve a pat on the back for your sharing. I wish you can update articles often. I hope I could read them everyday. Your posts offer advice to me. Thanks very much! apps email-with-love,autoketing e-mail with love, http://dichvuvina.vn,https://dichvuvina.vn/dang-ky-goi-cuoc-6tmaxs-vinaphone.html

    ReplyDelete

Post a Comment