What causes the object type to shift away from 'subscribe'?

Currently, I am facing an issue with retrieving a Coupon object from the server using a REST API in combination with Angular. The problem arises when I attempt to access the 'subscribe' method - within the 'subscribe', the object is of type 'Coupon', but outside of it, the object becomes 'undefined'.

Is there a way for me to maintain the type of the object outside of the 'subscribe' method and use it in other components?

log - 1 :
company-coupons.component.ts:24 **undefined**

log - 2 :
company.service.ts:32 
**Coupon {id: 44, title: "Test", startDate: "2000-01-01", endDate: "2000-02-02", category: 3, …}**


 fetchAllCoupons() {
this.storagService.getCompanyCoupons().subscribe(
  coupons => {
    this.coupons = coupons
    this.coupon = new Coupon(
      coupons[0].amount,
      coupons[0].category,
      coupons[0].endDate,
      coupons[0].id,
      coupons[0].imageURL,
      coupons[0].price,
      coupons[0].startDate,
      coupons[0].title,
    )
    console.log(this.coupon);
  })

}

getCompanyCoupons(): Observable<Coupon[]> {
const params = new HttpParams()
  .set("token", this.token)
return this.http.get<Coupon[]>('http://localhost:8080/api/company/get_company_coupons', { params })

}

getCoupons() {
this.fetchAllCoupons()
return this.coupons

}

EDIT: To clarify my question further, I am facing the issue of the object being 'undefined' only outside of the 'subscribe' method. I am looking for a solution to maintain its type outside the subscribe in other components.

Answer №1

It seems that the issue with your sample is that the getCoupons() function does not properly wait for fetchAllCoupons() to finish fetching data.

Here is a breakdown:

1: Call getCoupons()

2: Call fetchAllCoupons() (inside getCoupons())

3: Execute the rest API call (inside fetchAllCoupons())

4: Return this.coupons (inside getCoupons())

5: The response from fetchAllCoupons() comes back later.

You can try utilizing Promises to ensure that fetchAllCoupons() completes before moving on.

fetchAllCoupons() {
    return new Promise((resolve, reject) => {
        this.storageService.getCompanyCoupons().subscribe(
        coupons => {
            this.coupons = coupons
            this.coupon = new Coupon(
                coupons[0].amount,
                coupons[0].category,
                coupons[0].endDate,
                coupons[0].id,
                coupons[0].imageURL,
                coupons[0].price,
                coupons[0].startDate,
                coupons[0].title,
            )
            console.log(this.coupon);
            resolve("some argument");
       },
       (error) => reject())
    });
}

async getCoupons() {
    await this.fetchAllCoupons();
    return this.coupons;
}

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

Methods for resolving a ViewStyle typescript issue in react native

Trying to pass a width parameter into StyleSheet is causing an error like this: <View style={styles.children(width)}>{children}</View> Here's how I'm trying to use it: const styles = StyleSheet.create({ modalContent: { flex: ...

What's the best way to maintain the return type of a function as Promise<MyObject[]> when using forEach method?

I am currently working with a function called search, which at the moment is set up to return a type of Promise<MyObject[]>: export function search(args: SearchInput) { return SomeInterface.performSearch(args) .then(xmlRequest =&g ...

What is the best way to toggle the visibility of the ng-bootstrap datepicker-popup component?

Is there a way to toggle the visibility of the ng-bootstrap datepicker-popup by setting a property to 'true' or 'false'? In my form, I have the following snippet and I only want to show the entire div section if the user chooses to inp ...

Webpack compilation encountering an issue

I encountered an error while attempting to run my angular2 project. This issue arose after transitioning from a PC with Ubuntu to MacOS X. The Node version is 7.7.4, and the npm version is 4.1.2. I am executing npm webpack-dev-server --inline --progress ...

Encountering a ng2-charts bug during Angular app testing

I encountered the TypeError: Cannot read property 'getBasePixel' of undefined error while running tests with a component that has a chart. Despite searching for solutions, I couldn't find any relevant information. I ensured the charts module ...

Having difficulty installing node-sass in an Angular project

Having downloaded a repository from an existing Angular project, I proceeded to run sudo npm install within the project. While all packages were successfully installed, the node-sass package continued to cause issues. Upon completion of the installation ...

Error encountered during Angular unit testing: Unable to read the 'id' property of a null value. (Jasmine, Karma)

I am currently working on writing unit tests for a specific component in my Angular application. The component uses a currentUser variable both in the component logic and the HTML template. I have hardcoded this variable by mocking it in every test using c ...

Google Maps API Version 3 now allows for custom overlays to be hidden when they overlap

I have implemented multiple custom overlays on a map for various cities and I am trying to manage the overlapping ones by hiding or collapsing them. My goal is to display and expand overlays with the highest population whenever there is available space. M ...

Manually Enroll Node Module

Question: I am tackling a challenge in my TypeScript project where I need to interact with multiple APIs that are not available locally on my computer, but exist on the web. The code compiles without issues on my local machine as I have all the API declar ...

Tips for locating the beginning and conclusion of a RxJS.ajax request?

I'm utilizing the RxJS.ajax call to verify the availability of a product in the database. The response from this call typically takes between 2 to 4 seconds. During that retrieval time, I would like to show a message indicating "searching for product" ...

The karma Jasmine test failed to invoke the async callback within the timeframe set by the jasmine.DEFAULT_TIMEOUT_INTERVAL

I am facing an issue with my Angular4 unit tests using karma/jasmine. When I run the tests on PhantomJS browser locally, everything works fine. However, when I attempt to run the same tests on Jenkins (on PhantomJS), I encounter the following error: Stack ...

Node.js: Handling Undefined Request Parameters

My get route is set up to receive two parameters "limit" and "page". router.get('/:limit/:page', userController.list); class UserController{ public list(req:Request, res:Response): void{ const limit:number = +req.params.limit || 25; ...

Error encountered: 'applePaySession.completeMerchantValidation' is not a valid object reference when attempting to process a successful apple pay payment

So, I'm having an issue with the user's payment going through but encountering undefined value when checking compatibility. I've been trying to debug this problem in my code snippet below: setCanDisplayApplePay() { var client = n ...

Tips for automatically scrolling the Google Maps view in a React application

After implementing the google-map-react package, I have designed a TypeScript MapView component with the following code snippet. export function MapView<I extends Mappable>({ getData }: MapViewProps<I>): JSX.Element { const [mapZoom, setMapZo ...

Nested arrays in an Angular interface

As a newcomer to Angular with a background in Java, I am accustomed to setting up classes as data structures for my information. However, after doing some research, I have learned that interfaces should be used instead. I am facing an issue understanding ...

Angular 8 throws a TS2339 error, yet the code is functioning perfectly and delivering the desired output

Upon compiling my code, I encountered the following error: ERROR in src/app/home/home.component.ts:13:37 - error TS2339: Property 'name' does not exist on type 'string | Type'. Property 'name' does not exist on type &ap ...

What is the proper way to specify the type for a proxy that encapsulates a third-party class?

I have developed a unique approach to enhancing Firestore's Query class by implementing a Proxy wrapper. The role of my proxy is twofold: If a function is called on the proxy, which exists in the Query class, the proxy will direct that function call ...

Update to Material-UI 4.8.1 - Is there a different method for defining the `component` property now?

Note: Please note that there was a bug in version 4.8.x which caused this issue. To resolve it, make sure to upgrade to version 4.9.0 or above. In the initial version 4.8.0, the following code would compile and run smoothly: <DialogContent> {/* us ...

Troubleshooting Angular error encountered during the execution of the 'ng build --prod' command

While developing my Angular application, I encountered an issue when using the ng build --prod command. Surprisingly, everything was working fine with ng serve. I am struggling to figure out what the problem could be. ERROR in: Unable to locate resource a ...

The directive is dynamically altering the disable attribute of its parent element

I am faced with a scenario where I have both a button and a directive in my template. The button can be disabled based on certain parameters defined in the template itself, as well as by the directive (it gets disabled in case of a double click event). B ...