It is deprecated method which allows to create Observable by providing the values in the argument, internally it calls constructor method to create Observable. It is also possible to create Observable by using constructor directly.
Example
Create observable using create method
1 import { Component, OnInit } from "@angular/core";
2 import { Observable } from "rxjs";
3
4 @Component({
5 selector: 'app-root',
6 templateUrl: './app.component.html',
7 styleUrls: ['./app.component.less']
8 })
9
10 export class AppComponent implements OnInit {
11
12
13 obsConstructor = Observable.create((observer: any) => {
14 observer.next('1')
15 observer.next('2')
16 observer.next('3')
17
18 observer.complete()
19 });
20
21 ngOnInit() {
22
23
24 this.obsConstructor
25 .subscribe((value: any) => console.log(value),
26 (error: any) => console.log('error occured.. '),
27 () => console.log('Completed'));
28 }
29 }
In the above example, a component created with observable object that created by using create() method. A create() method expects a function that will be called with observable object when observable method subscribe() called. It emits three string type value using next() method and complete using complete() method.
A component life cycle method ngOnInit() method called once a component template rendered on browser. It subscribe observable object that receives value when observable emit value, if value emitted successfully, it execute success function, in case error, it calls error function and at last it executes complete function.
Example with function
1 function emitNumber(observer: Observer<number>) {
2
3 observer.next(1);
4 observer.next(2);
5 observer.next(3);
6 observer.complete();
7
8
9
10
11
12 return {unsubscribe() {}};
13 }
In the above example, a function emitNumber() is define that receives an observable object of type number. A number will be emitted using next() method by passing a number. and completed at the end. It returns object that includes unsubscribe() method.
Create Observable and subscribe()
1 const sequence = new Observable(sequenceSubscriber);
2
3
4 sequence.subscribe({
5 next(num) { console.log(num); },
6 complete() { console.log('Finished sequence'); }
7 });
In the above example, a Observable object is created by passing a function that define earlier. A observable is subscribe using subscribe() method that calls specified function which will emit value using next() method, when a value receive successfully, it executes next() method, in case error, error function gets executed, if specified and on completion a complete() method called.
Related options for your search