1
votes

I have an existing Angular 2 project that I ported to Angular 6 and now my HTTP-observable is not running any longer. As far I read it is about different operations of the new observable.

My service returns an observable. This I subscribe in the component and set interval and startindex.

How can I do that in Angular 6?

// SERVICE 
@Injectable ()
export class ViewService
{
  constructor (private http : HttpClient)
  {      }

  foo () : Observable <any>
  {
    return this.http.get ("http://blabla",
      {responseType: "json"});
  }
}



// COMPONENT
export class ViewComponent
{
  constructor (private vs : ViewService)
  {      }

  ngOnInit ()
  {
    this.vs.foo ().interval (1000).startWith (0).subscribe (
      (resp) =>
      {
      });
  }
}

Error

Error: error TS2339: Property 'interval' does not exist on type 'Observable'

Using rxjs 6.0.0

2
has any error ? - Hasan Fathi
What is you current RxJs version right now ? - Ulrich Dohou
You may want to check this stackoverflow.com/a/42885710/6261137 - Ulrich Dohou

2 Answers

4
votes

First you have to import interval from rxjs.

import { interval } from 'rxjs';

Import startWith and also you have to import mergeMap from rxjs/operators.

import { startWith, mergeMap } from 'rxjs/operators';

Then you could use them like this:

interval(1000).pipe(
  startWith(0),
  mergeMap(iRes => this.vs.foo())).subscribe(resp => {
    console.log(resp);
  });

Hope this will helps you!

1
votes

There are a couple of breaking changes in RxJS v6 that has been adopted by Angular6 that you need to be aware of:

  1. The different way of import statement of observables and operators. So you will need to add operators in this way at the top of the component controller:

    import { interval } from 'rxjs';
    import { startWith, mergeMap } from 'rxjs/operators';
    
  2. Use pipe() as a method to chain your operators, the old way of chaining them will not work:

    // COMPONENT
    export class ViewComponent
    {
        constructor (private vs : ViewService) {}
    
        ngOnInit () {
           const obs$ = interval(1000).pipe( // This is your main observer chain
               startWith(0),
               mergeMap(res => this.vs.foo()) // This will start a sub-chain of observer that is isolated to your main chain
                  .subscribe(res => console.log('subscription of the sub-chain: ', res))
           )
    
           obs$.subscribe(res => console.log('subscription of main chain: ', res));
        }
     }
    

If you are still confusing, please watch the video from Ben Lesh and learn what has been changed in RxJS v6: https://www.youtube.com/watch?v=JCXZhe6KsxQ