Unreachable code Detected at angular

Asked

Viewed 32 times

1

Watch this code snippet;

this.notificationService.notify(`cadastro feito com sucesso`)  

I created a project in Angular, if it is an Ecommerce system, every time I select a product it can notify the message on screen perfectly using this code snippet above, but when I use this code snippet in an observable method it gives problem.

In this code it works smoothly;

removeItem(item: CartItem) {
      this.items.splice(this.items.indexOf(item), 1)
      this.notificationService.notify(`Você removeu um item ${item.menuItem.name}`);
  }

But this code below does not work;

checkOrder(order: Order): Observable <string> {

  const headers = new Headers()
  headers.append('Content-Type', 'application/json')
  return this.http.post(`${this.url}/orders`, 
           JSON.stringify(order),
            new RequestOptions({ headers: headers }))
            .map(response => response.json())

        this.notificationService.notify(`cadastro feito com sucesso`)  

    }

He give this error message => order.service.ts (55,10): Unreachable code detected.

The error I made is because it has a line of code after a Return.

To notify in a successful reply, simply call the Observable subscribe or use the operator’s. For example, but I don’t know how to modify my code to work despite knowing in theory how to solve.

I need help.

1 answer

2


As you said yourself, it does not make the notifty because it is after a Return. To solve, where you call the method checkOrderyou can call notify inside the subscribe.

this.service.checkOrder(parametroquevocepassou)
.subscribe(res => {
   this.notificationService.notify(`cadastro feito com sucesso`)  
})
  • 1

    That suggestion would be a good alternative if it were used in the component class, but because of my design structure there’s no way I can put it in the component class, would there be a way for the code to stay in the service class, I’m trying trouble because of lack of experience, I require a little patience.

  • 1

    @wladyband without problems, we are all learning at all times. Is there any specific reason why the notification doesn’t stay in the component? After all, the result you will only know whether or not the request was successful by subscribing to the method.

  • 1

    is quiet, because your suggestion made me open my mind to solve the problem otherwise, but rest assured that your suggestion was good, thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.