ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Create observable from a string, array & object in angular

In this tutorial, we will show you how to create observable using create, of, from operators in Angular. We can use them to create new observable from the array, string, object, collection or any static data. Also learn the difference between the Of & From operators. If you are new to observable, we recommend you to read the Angular observable before continuing here.

Observable creation functions

There are many ways to create observable in Angular. You can make use of Observable Constructor as shown in the observable tutorial. There are a number of functions that are available which you can use to create new observables. These operators help us to create observable from an array, string, promise, any iterable, etc. Here are some of the operators

  • create
  • defer
  • empty
  • from
  • fromEvent
  • interval
  • of
  • range
  • throw
  • timer
  • All the creation related operators are part of the RxJs core library. You can import it from the ‘rxjs’ library

    Create

    The Create method is one of the easiest. The create method calls the observable constructor behind the scene. Create is a method of the observable object, Hence you do not have to import it.

                                  
    
    ngOnInit() {
     
       //Observable from Create Method
       const obsUsingCreate = Observable.create( observer => {
         observer.next( '1' )
         observer.next( '2' )
         observer.next( '3' )
     
         observer.complete()
       })
       
        obsUsingCreate
          .subscribe(val => console.log(val),
                  error=> console.log("error"),
                  () => console.log("complete"))
    }
     
     
     
    ****Output *****
    1
    2
    3
    Complete
     
                                
                            

    Observable Constructor

    We looked at this in the previous tutorial. There is no difference between the Observable.create method and observable constructor. The Create method calls the constructor behind the scene.

                                  
     
    ngOnInit() {
       //Observable Using Constructor
       const obsUsingConstructor = new Observable( observer => {
          observer.next( '1' )
          observer.next( '2' )
          observer.next( '3' )
     
          observer.complete()
       })
     
       obsUsingConstructor
            .subscribe(val => console.log(val),
                    error=> console.log("error"),
                    () => console.log("complete"))
    }
     
     
    ****Output *****
    1
    2
    3
    complete
     
                                
                            

    Of Operator

    The Of creates the observable from the arguments that you pass into it. You can pass any number of arguments to the Of. Each argument emitted separately and one after the other. It sends the Complete signal in the end.

    image

    To use of you need to import it from rxjs library as shown below.

                                  
    
    import { of } from 'rxjs';
     
                                
                            

    observable from an array

    Example of sending an array. Note that the entire array is emitted at once.

                                  
    
    ngOnInit() {
      const array=[1,2,3,4,5,6,7]
      const obsof1=of(array);
      obsof1.subscribe(val => console.log(val),
               error=> console.log("error"),
              () => console.log("complete"))
     
    }
     
     
    **** Output ***
    [1, 2, 3, 4, 5, 6, 7]
    complete
     
                                
                            

    You can pass more than one array

                                  
     
    ngOnInit() {
      const array1=[1,2,3,4,5,6,7]
      const array2=['a','b','c','d','e','f','g']  
      const obsof2=of(array1,array2 );
      obsof2.subscribe(val => console.log(val),
               error=> console.log("error"),
              () => console.log("complete"))
     
    }
     
     
    **** Output ***
    [1, 2, 3, 4, 5, 6, 7]
    ['a','b','c','d','e','f','g']
    complete
     
                                
                            

    observable from a sequence of numbers

    In the following example, we pass 1,2 & 3 as the argument to the from. Each emitted separately.

                                  
    
    ngOnInit() {
        const obsof3 = of(1, 2, 3);
        obsof3.subscribe(val => console.log(val),
          error => console.log("error"),
          () => console.log("complete"))
     
    }
     
     
     
    **** Output ***
    1
    2
    3
    complete
                                
                            

    observable from string

    We pass two strings to the of method. Each argument is emitted as it is.

                                  
     
     ngOnInit() {
        const obsof4 = of('Hello', 'World');
        obsof4.subscribe(val => console.log(val),
          error => console.log("error"),
          () => console.log("complete"))
    }
     
     
    **** Output ***
    Hello
    World
    complete
                                
                            

    observable from a value, array & string

    We can pass anything to the Of operator. It justs emits it back one after the other.

                                  
     
     ngOnInit() { 
        const obsof5 = of(100, [1, 2, 3, 4, 5, 6, 7],"Hello World");
        obsof5.subscribe(val => console.log(val),
          error => console.log("error"),
          () => console.log("complete"))
    }
     
    **** Output ***
    100
    [1, 2, 3, 4, 5, 6, 7]
    Hello World
    complete
     
                                
                            

    From Operator

    From Operator takes only one argument that can be iterated and converts it into an observable.

    You can use it to convert

    1. an Array
    2. anything that behaves like an array
    3. Promise
    4. any iterable object
    5. collections
    6. any observable like object

    It converts almost anything that can be iterated to an Observable.

    To use from you need to import it from rxjs library as shown below.

                                  
     
    import { from } from 'rxjs';
     
                                
                            

    observable from an array

    The following example converts an array into an observable. Note that each element of the array is iterated and emitted separately.

                                  
    
    ngOnInit() {
     
        const array3 = [1, 2, 3, 4, 5, 6, 7]
        const obsfrom1 = from(array3);
        obsfrom1.subscribe(val => console.log(val),
          error => console.log("error"),
          () => console.log("complete"))
     
    }
     
    *** Output ****
    1
    2
    3
    4
    5
    6
    7
    complete
     
                                
                            

    Observable from string

    The from operator iterates over each character of the string and then emits it. The example is as shown below.

                                  
     
    ngOnInit() { 
      const obsfrom2 = from('Hello World');
        obsfrom2.subscribe(val => console.log(val),
          error => console.log("error"),
          () => console.log("complete"))
    }
     
     
    *** Output ****
    H
    e
    l
    l
    o
     
    W
    o
    r
    l
    d
    complete
     
                                
                            

    Observable from collection

    Anything that can be iterated can be converted to observable. Here is an example using a collection.

                                  
     
    ngOnInit() {
          let myMap = new Map()
          myMap.set(0, 'Hello')
          myMap.set(1, 'World')
          const obsFrom3 = from(myMap);
          obsFrom3.subscribe(val => console.log(val),
            error => console.log("error"),
            () => console.log("complete"))
    )
     
    *** output ***
    [0, "Hello"]
    [1, "World"]
    complete
     
                                
                            

    Observable from iterable

    Any Iterable types like Generator functions can be converted into an observable using from the operator.

                                  
     
    ngOnInit() {
         const obsFrom4 = from(this.generateNos())
          obsFrom4.subscribe(val => console.log(val),
          error => console.log("error"),
          () => console.log("complete"))
    }
     
    *generateNos() {
       var i = 0;
       while (i < 5) {
         i = i + 1;
         yield i;
      }
     
     
    *** Output ***
    1
    2
    3
    4
    5
     
                                
                            

    Observable from promise

    Use it to convert a Promise to an observable

                                  
     
    ngOnInit() {
        const promiseSource = from(new Promise(resolve => resolve('Hello World!')));
        const obsFrom5 = from(promiseSource);
        obsFrom5.subscribe(val => console.log(val),
          error => console.log("error"),
          () => console.log("complete"))
    }
     
    *** Output ****
    Hello World
    complete
     
                                
                            

    Of Vs From

    Of from
    Accepts variable no of arguments Accepts only one argument
    emits each argument as it is without changing anything iterates over the argument and emits each value

    Summary

    We can use the Create method or Observable Constructor to create a new observable. The Of operators is useful when you have array-like values, which you can pass it as a separate argument to Of method to create an observable. The From Operate tries to iterate anything that passed into it and creates an observable out of it. There are many other operators or methods available in the RxJS library to create and manipulate the Angular Observable. We will learn a few of them in the next few tutorials