Observing the World with TypeScript

Sorry, I am quite new to this and facing a bit of confusion.

So, I have a CalendarService which includes a method called getYear(id: string). The structure of my Year model is as follows:

export class Year {
    id: string;
    number: Number;
    months: Month[];
    weeks: Week[];
}

My objective is to retrieve data from Months[] such as name, numberOfDays, etc.

This is the implementation of my service:

@Injectable()
export class CalendarService {
  endPoint: string;
  private _calendarUrl = '/api/mycalendar';

  months: Month[];
  year: Date;

  constructor(private http: HttpClient) {

  }

  getYear(id: string): Observable<Year> {
    return this.http.get(this._calendarUrl + '?id=' + id)._catch(this.handleError);
  }

  getYears() {
    return this.http.get(this._calendarUrl)
                     .map((res: Response) => res.json())
                    ._catch(this.handleError);

  }

  getMonths(yearId: string) {
    // Retrieve year data from database
    const year =  this.getYear(yearId); 
    
    // Accessing the months
    this.months = year.
  }


  private handleError(error: any) {
    const errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.log(errMsg);
    return Observable.throw(error);
  }

}

Answer №1

Give this a shot.

@Injectable()
export class CalendarService {
  endpoint: string;
  private _calendarEndpoint = '/api/mycalendar';

  monthsArray: Month[];
  selectedYear: Date;

  constructor(private http: HttpClient) {

  }

  fetchSelectedYear(id: string): Observable<Year> {
    return this.http.get(this._calendarEndpoint + '?id=' + id)._catch(this.handleError);
  }

  fetchYears() {
    return this.http.get(this._calendarEndpoint)
                     .map((res: Response) => res.json())
                    ._catch(this.handleError);

  }

// Perform the API call here and subscribe for the response.
  obtainMonthsForYear(yearId: string) {
    const yearData =  this.fetchSelectedYear(yearId).subscribe((response) => {
          this.monthsArray = response.
     }); 
  }


  private handleError(error: any) {
    const errorMessage = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.log(errorMessage);
    return Observable.throw(error);
  }

}

Answer №2

When making the getYear API call, it will return an observable. Therefore,

It is essential to subscribe to the returned observable

fetchMonths(yearId: string) {
    const yearData =  this.getYear(yearId).subscribe((response) => {
          this.months = response.months // or response.data.months
     });  

}

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 preserving scroll location on Angular components (not the window) when navigating

My current layout setup is like this: https://i.sstatic.net/hOTbe.png In essence <navbar/> <router-outlet/> The issue I'm facing is that the router-outlet has overflow: scroll, making it scrollable (just the outlet section, not the ent ...

The activation of [routerLinkActive] triggers an error related to the data.split function

In my lazy loaded module, I have implemented simple routing as shown below: <div id="nav"> <div class="nav-content"> <div class="nav-item" [routerLink]="'basic'" [routerLinkActive]="active-nav"> <span ...

Typescript's default string types offer a versatile approach to defining string values

Here is an example code snippet to consider: type PredefinedStrings = 'test' | 'otherTest'; interface MyObject { type: string | PredefinedStrings; } The interface MyObject has a single property called type, which can be one of the ...

Expect a reply within the loop

One of my endpoints takes some time to generate data, and I have another endpoint to retrieve that generated data. I make the initial call using await, extract the ID from the response, and then keep calling the second endpoint until the status is not "Suc ...

Why is there a false positive in the onChange event for the number type in React TypeScript?

I encountered an error on line 24 Argument of type 'string' is not assignable to parameter of type 'SetStateAction'.ts(2345) This issue occurred while working with TypeScript for a React experiment. const App: React.FC = () => ...

Creating TypeScript modules for npm

I have been working on creating my first npm module. In the past, when I used TypeScript, I encountered a challenge where many modules lacked definition files. This led me to the decision of developing my module in TypeScript. However, I am struggling to ...

The command 'prefix -g' is encountering an error and is not recognized as a valid command during the installation process of Angular

Microsoft Windows [Version 10.0.16299.309] (c) 2017 Microsoft Corporation. All rights reserved. C:\Users\Futluz>cd desktop/angular-cli-master/angular-cli-master C:\Users\Futluz\Desktop\angular-cli-master\angular-cli- ...

Hidden field in Angular 2 form has an invalid property

I am working with a form object called "formObject" and I am trying to store the validity status of the form in a variable called form.isFormValid. Any suggestions or assistance would be greatly appreciated. export class FormObject { public isFormValid: ...

Creating multiple CRUD components in Angular 2: which is better, using routing or a parent component

My application consists of multiple sections that act as independent CRUD components. There are two approaches that I am aware of: Utilize a parent component with ngIfs to manage the view/edit/add operations of child components Implement subrouting wit ...

"Error occurs as a result of an unspecified attribute in the map

Hello, I am currently traversing a tree structure recursively. To handle undefined nodes in the tree, I have implemented guards to prevent any failures. However, during the mapping of children nodes, I encountered the following error: Error Output Adri ...

Having trouble retrieving data in the service. Unable to subscribe to it from other components

userService.ts private APIUrl: string = environment.APIUrl; constructor(private inService: API, private httpClient: HttpClient) { } private _userDataDashboard$ = new ReplaySubject<UserDetailsDashboard>(1); getUserDetailsSubject(): Obser ...

Protractor enables horizontal scrolling for a Div element

My struggle to scroll to the right persists despite all attempts I experimented with various solutions, but none seem to work await browser.executeScript('arguments[0].scrollIntoView(true)',element.getWebElement()) The issue still remains unr ...

Can you please explain to me the purpose of the ncu -u command?

Struggling to update my Angular project in Visual Studio to a specific version of Angular. Instead of following the tutorial that provided me with the latest Angular version, I wanted to install version 6 specifically. So, I ran npm install -g @angular/ [ ...

Troubleshooting the TS2559 error when using radium in React typescript: CSSProperties type mismatch

Looking to integrate Typescript into React and incorporate some styling using Radium. I understand that JSX style does not support media queries, but I'm unsure how to resolve this issue. Can anyone provide guidance? Thank you! Encountering errors w ...

Tips for managing the output of an asynchronous function in TypeScript

The casesService function deals with handling an HTTP request and response to return a single object. However, due to its asynchronous nature, it currently returns an empty object (this.caseBook). My goal is for it to only return the object once it has b ...

Ways to adjust the size of a Primeng autocomplete with multiple selections?

I'm new to Angular and I'm attempting to adjust the width of a primeng auto complete component in order to fill the column of a table. I've already experimented with using style="width: 100%" but that approach hasn't yielded any result ...

In Angular 15, CSS override configurations do not function as intended

Exploring the world of Angular is exciting, and I am a newcomer to it. Currently, I am tackling an innovative Angular 15 project that makes use of the Material library. My current predicament lies in the fact that none of the CSS overrides appear to be tak ...

Converting hexadecimal to binary using Javascript or Typescript before writing a file on an Android or iOS device

Hey everyone! I'm facing a puzzling issue and I can't seem to figure out why it's happening. I need to download a file that is stored in hex format, so I have to first read it as hex, convert it to binary, and then write it onto an Android/ ...

Is there a way to insert a Highchart Image into a spreadsheet in Excel?

Struggling to insert a Highchart's chart image into an Excel file? The goal is to utilize the current "Export Excel" button on a website to export a static image of the Highchart displayed on the webpage directly into an excel spreadsheet. Provided be ...

An issue has occurred due to an illegal state while attempting to utilize two modules within a single

When a user logs into my system, they are redirected to the profile page /profile/profile.component.ts after entering correct login credentials. Now, I want to implement an additional module for protected pages/components like the profile page and redirect ...