strike on subscribe while coding in angular. Its says depreciated on hover

79 views Asked by At

I am still figuring out angular. I am working a form to post user details. The form is working and i can see the values in database. Problem is i see a strike on subscribe and on hover it shows the following

'@deprecated — Instead of passing separate callback arguments, use an observer argument. Signatures taking separate callback arguments will be removed in v8.'.

But its working fine. Can anyone help me. Below is the part of code

  onSubmit(): any {    
 this.userService.Signup(this.signupForm.value)
    .subscribe(() => {
        console.log('Data added successfully!')
        this.ngZone.run(() => this.router.navigateByUrl('/'))
      }, (err:any) => {
        console.log(err);
    });
  }

i have just tried few code changes i could find on google

2

There are 2 answers

0
Mahya Bagheri On

You should add your subscription to an array of Subscription[] and then unsubscribe all your subscriptions in ngOnDestroy to avoid seeing this deprecation message on hover.

subscriptions: Subscription[];

onSubmit(): any {

 const userServiceSubscription =    
 this.userService.Signup(this.signupForm.value)
        .subscribe({
            next: () => {
                console.log('Data added successfully!')
                this.ngZone.run(() => this.router.navigateByUrl('/'))
            },
            error: (err: any) => {
                console.log(err);
            }
        })

 }

 ngOnDestroy(): void {
    this.subscriptions.forEach(s => s.unsubscribe());
 }
0
Naren Murali On

You need to specify it as an object, with three properties, next, error and complete. Also we need to add the subscription inorder to avoid memory leaks.

subscription: Subscription = new Subsciption();

onSubmit(): any {
    this.subscription.add(
        this.userService.Signup(this.signupForm.value)
            .subscribe({
                next: () => {
                    console.log('Data added successfully!')
                    this.ngZone.run(() => this.router.navigateByUrl('/'))
                },
                error: (err: any) => {
                    console.log(err);
                }
            })
    );
}

ngOnDestroy(): void {
    this.subscription.unsubscribe();
}