How to get data.next() and data.complete() here in the following code?

Viewed 44

How can I get the data.next() and data.complete() in the following code. isn't data here acts as observer?

when I am trying to call those method I am getting an error

component.ts file

 this.authservice.registerform(form).subscribe(data => {
     data. ?
     this.ifsuccess = true;
     this.timer = setInterval(() => {
      this.router.navigate(['']);
     }, 1200);});

Service.ts

 registerform(data): Observable<any>{
return this.httpclient.post('http://localhost:3000/login',data);

}

I am a beginner to Angular and rxjs. Please help on this.

1 Answers

isn't data here acts as observer?

No, in your example data is the emitted ("next") value.

When you subscribe to an observable, you can pass three different parameters, which are handlers for next, error, and complete.

example:

someObservable$.subscribe(
    next => console.log(`next value is: ${next}`),
    err  => console.log(`error is: ${err}`),
    ()   => console.log('someObservable$ completed!) 
);

In your case, you are only providing the first handler to the subscribe(), method. You can access the next value simply by using the param name data:

this.authservice.registerform(form).subscribe(
    data => {
        // 'data' refers to the emitted value
        this.ifsuccess = true;
        this.timer = setInterval(() => {
            this.router.navigate(['']);
        }, 1200);
    }
);

If you need to handle completion or error, simply provide the other handlers as well:

this.authservice.registerform(form).subscribe(
    data => {
        // 'data' refers to the emitted value
        this.ifsuccess = true;
        this.timer = setInterval(() => {
            this.router.navigate(['']);
        }, 1200);
    },
    error => console.log('error occurred!'),
    ()    => console.log('registerform call completed')
);

It is also possible to pass a full observer object to the subscribe() method, instead of individual handler methods:

const myObserver = {
    next:    val => console.log(`next val: ${next}`),
    error: error => console.log(`error: ${error}`),
    complete: () => console.log('complete!')
};

someObserver$.subscribe(myObserver);

Here's a StackBlitz with a sample.

Related