What is the proper way to access variables within an RxJS subscribe() block?

Seeking guidance on utilizing angular2 and facing challenges extracting a value within the subscribe() function. I am aware it is currently returning null. Any advice provided would be greatly appreciated. Thank you :)

Below is the code snippet in question:


this.deliveryService.deliveryCancel(rowInfo.branchId, rowInfo.id).subscribe(
    res => {
        var data = res.json();
        this.getDeliveryList();
        this.msgs.push({ severity: 'success', summary: 'Info', detail: rowInfo.deliveryStatus });
    },
    err => {
        this.errMessage = <any>err;
        this.msgs.push({ severity: 'error', summary: 'Error', detail: this.errMessage });
    }
);

console.log(data);

deliveryCancel()


 deliveryCancel(branchId, deliveryId) {
    const headers = new Headers({
      'Content-Type': 'application/json'
    });
    return this.http.put(this.testUrl + '/admin/branches/' + branchId + '/deliveries/' + deliveryId + '/cancel', {
      headers: headers
    })
      .catch(handleError);
  }

Answer №1

Accessing res.json() directly is not possible. Ensure to initialize 'data' as a class variable. Here's a revised approach:

data = {};

this.deliveryService.deliveryCancel(rowInfo.branchId, rowInfo.id).subscribe(
          res => {
            this.data = res['_body'];
            this.getDeliveryList();
            this.msgs.push({ severity: 'success', summary: 'Info', detail: rowInfo.deliveryStatus });
          },
          err => {
            this.errMessage = <any>err;
            this.msgs.push({ severity: 'error', summary: 'Error', detail: this.errMessage });
          }
        );

        console.log(data);

Answer №2

While this question may not specifically pertain to Angular, it delves into the realm of JavaScript and how asynchronous behavior can disrupt the flow of execution.

Subscribing ensures that upon any error or success returned by deliveryCancel(), either the res function or err function will be triggered.

It's important to note that your console.log(data) statement is only executed once and is not part of those functions.

To achieve the desired outcome, consider the following approach:

this.deliveryService.deliveryCancel(rowInfo.branchId, rowInfo.id).subscribe(
  res => {
    this.data = res['_body'];
    this.getDeliveryList();
    this.msgs.push({ severity: 'success', summary: 'Info', detail: rowInfo.deliveryStatus });
    console.log(data);
  },
  err => {
    this.errMessage = <any>err;
    this.msgs.push({ severity: 'error', summary: 'Error', detail: this.errMessage });
    console.log(data);
  }
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for updating routerlink in navigation bar in Angular 4

I'm encountering an issue with routing to the wrong routelink. How can I prevent this from happening? My apologies for my lack of experience. The error message displayed in the Chrome console is: ERROR Error: Uncaught (in promise): Error: Cannot mat ...

Is the HTTP request not being made in this code snippet?

DataService: export class DataService { constructor(private _http: HttpClient) { Custom.Socket.next('https://reqres.in'); } fetchData(url): any { return Custom.Socket .switchMap((x)=> this._http.get( x + url)); } s ...

Issue with Angular Routing When Deployed

After developing a website utilizing Angular 6 and hosting it on GitHub, I incorporated Routing to automatically direct users to the '/home' page instead of the main '/' page. You can access the project by clicking on this project link. ...

Issue with CSS files in Jest"errors"

I'm currently facing an issue while trying to pass my initial Jest Test in React with Typescript. The error message I am encountering is as follows: ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.App ...

Is there a way to enhance a generic parameter using another generic parameter in TypeScript?

I am struggling with repetitive code that involves a type with minor variations: import { ComponentPropsWithRef, ElementType } from "react"; interface PackshotPropsBase { a: string } interface PackshotPropsWeb { b: string } export type Ele ...

The requested file could not be located, specifically the ng2-page-scroll

I encountered an issue while trying to use the ng2-page-scroll library. Following their instructions resulted in a "file not found" error for ng2-page-scroll. It seems like there may be an error in the systemjs.config file. Does anyone know how to resolve ...

Angular - Eliminate module during build process

In my current project, there is a module called data-generator that is only used during development mode (when running `npm start`). When building the application (using `npm run build`), this module is not needed. Is there a way to exclude it from the pro ...

Examine every character in the text to determine if it qualifies as a separator

Can anyone assist me with a task I'm working on? I'm trying to write a function that checks the letters of a string. I attempted to use both a for loop and a foreach loop, but I couldn't get it to work properly :( let input = this.tagsFor ...

Can an @ArgType be created using a combination of union @Field?

Is there a way for me to define an input / argtype that could either be a ContactCreate or a ContactRead? I'm uncertain if it's feasible. import { ContactCreate } from 'contact/ContactCreate' import { ContactRead } from 'contact/C ...

Angular 2's version of the code above

Struggling to transition this code from angularjs to angular 2, appreciate any assistance if (settings != null && settings.checkSubscriptionForVip === true) { return this.user.hasVipAccess().then(function(hasVipAccess) { hasV ...

Angular: Issue encountered when accessing nested properties within an interface due to reading properties of undefined

Encountering difficulties with utilizing nested property interface. //Food Interface (food.interface.ts)// export interface Food { name: string; quantity?: string; description?: string; nutrients?: { calories?: number; protein?: number; carbs?: ...

Trigger on the cancellation or completion of a nested observable

I'm seeking a way to detect if an inner observable was not successfully completed (due to everyone unsubscribing) and then emit a value in that scenario. Something akin to defaultIfEmpty, but the current solution isn't effective. A trigger exis ...

How can one use an Angular Route to navigate to a distinct URL? Essentially, how does one disable matching in the process?

I'm working on a front-end Angular application and I need to add a menu item that links to an external website. For example, let's say my current website has this URL: And I want the menu item in my app to lead to a completely different website ...

Tips on how child component can detect when the object passed from parent component has been updated in Angular

In the child component, I am receiving an object from the parent component that looks like this: { attribute: 'aaaa', attribute2: [ { value }, { value }, { value }, ] } This object is passed to th ...

Implementing dynamic progress bar updates in an Angular application using Bootstrap

Seeking to create a progress bar in a Word object for a language vocabulary training app, displaying the number of correct and wrong answers. <div class="progress"> <div class="progress-bar progress-bar-striped progress-bar-a ...

Identify and handle errors effectively using TypeScript

I have a question regarding my Express server setup. Here is the code snippet: import express from "express"; import helmet from "helmet"; import cors from "cors"; const app = express(); app.use(helmet()); app.use(cors()); a ...

Troubleshooting Docker Angular+Nginx: Decoding the Mystery Behind Error Codes 403 and

Backend of my .net application is running on mssql and frontend is built with Angular. I have successfully configured Docker files and nginx.conf, but I am facing an issue specifically with Angular 17 within Docker. The main problem is that, when accessing ...

The JestImportMeta interface is mistakenly extending the ImportMeta interface, causing an error

While transitioning from jest version 27 to v29, I encountered this issue: node_modules/@jest/environment/build/index.d.ts:329:26 - error TS2430: Interface 'JestImportMeta' improperly extends interface 'ImportMeta'. The types returned ...

Angular MatDialog failing to display the gray overlay background

I am currently working with Angular 6 and have successfully integrated the theme into my project. The code snippet below shows how I open the dialog. constructor(private dialogo: MatDialog) { } ngOnInit() { this.dialogo.open(Carrega ...

Automatic completion of absolute paths in VS Code with the ability to click and view definitions through the configuration file js/tsconfig.json

In order to ensure that absolute paths function correctly, I have found that there are two key steps involved: the compilation process and configuring the code editor. I successfully managed the compilation aspect by utilizing babel-plugin-module-resolver ...