Utilizing Angular 2 to retrieve and assign object properties provided by a service to a local variable within a

My video service:

public getExercise(exerciseId): Observable<Exercise[]>{

        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers, withCredentials: true });

        return this.http.get(this.base_url + exerciseId + '/', options)
        .map(this.extractData)
        .catch(this.handleError);
}

In my template I have:

<!-- Show current level -->
<div align="center">
 <h6>Ihre aktuelle Intensitätsstufe ist {{intensity_level}}</h6>
</div>

<div *ngIf="showVideo" align="center" class="video-container">
        <iframe [src]="exercise_video_url | safe" frameborder="0" allowfullscreen></iframe>
</div>

And my component:

export class VideoPage implements OnInit {

    exercise: Exercise[];
    errorMessage: string;

    public exercise_id: number;
    public intensity_level: number;
    public rating: number;
    public exercise_video_url: string;
    public current_date: string;


    constructor(public navCtrl: NavController, public navParams: NavParams, public videoService: VideoService) {

        console.log(this.navParams.get('exerciseId'));
        this.exercise_video_url='';

        this.exercise_id=this.navParams.get('exerciseId');

    }

    ngOnInit(){

        this.getExercise()
    }

    getExercise(){

        this.videoService.getExercise(this.exercise_id)
            .subscribe(
                exercise => {
                    this.exercise = exercise;
                    console.log(this.exercise[0].video_url)

                },
                error => {
                    this.errorMessage = <any>error;
                });

         this.exercise_video_url=this.exercise[0].video_url;

    }   
}

However, the object properties are not being assigned to my local variables so that I can bind them on template. My service simply returns one object that's why I used this.exercise[0] and if I try to write the same line outside get(), it gives compilation error (which seems obvious). What should be done here?

The console line prints the url.

Answer №1

The issue at hand arises from the fact that you are assigning the video URL outside of the subscribe function.

fetchExerciseDetails(){

    this.exerciseService.fetchExercise(this.exercise_id)
    .subscribe(
        exercise => {
            this.exercise = exercise;
            console.log(this.exercise[0].video_url)
            // UPDATED LINE
            this.exercise_video_url=this.exercise[0].video_url;
        },
        error => {
            this.errorMessage = <any>error;
        });

    // PREVIOUS LINE
    // this.exercise_video_url=this.exercise[0].video_url;

}   

Answer №2

The response content needs to be mapped to the required Exercise model in your service. Here is how you can modify it:

public fetchExercise(exerciseId): Observable<Exercise[]>{

        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers, withCredentials: true });

        return this.http.get(this.base_url + exerciseId + '/', options)
        .map((response: Response) => <Exercise[]>response.json())
        .catch(this.handleError);
}

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

Choose the initial mat-option with mat-select functionality

In my app, I have several Angular Material select dropdowns with mat-options that are updated reactively based on other values (filtering of options). Here's an example: <mat-select #selects (selectionChange)='formChanges()' [placeholder ...

Updating a view based on an SVG object's geometric properties in Angular using effective change detection mechanisms

I'm unsure if there's a proper way to accomplish this in Angular... My goal is managing the overlap of text objects, essentially : Retrieve a list of objects with a date and text description from the backend. Display these objects on an SVG tim ...

When selecting an input within a div, the Angular onblur function is behaving erratically

How can I prevent the div from closing when I click on an input inside it after setting a tabindex to the div and closing it on blur? Solution for app.component.html: <button (click)="openToggle('toggle1')">Toggle 1</button> ...

Expecting null in Angular2/Jasmine tests can lead to browser crashes

I'm currently experiencing issues with testing a particular component. Here is the test that I am running: describe('SmpEventsNewCompactEventComponent', () => { const specService: SmpSpecService = new SmpSpecService(); describe(&ap ...

Collection of functions featuring specific data types

I'm currently exploring the idea of composing functions in a way that allows me to specify names, input types, and return types, and then access them from a central function. However, I've encountered an issue where I lose typing information when ...

Using Qwertz layout on Protractor, sending an exclamation mark is not possible

Trying to input an exclamation mark in a field using Protractor is proving to be difficult for me. Here's what I'm attempting: element(by.id('nom')).sendKeys('abc!'); But all I see in the field is abc. Upon adding a keyup ...

Populating datasets with relative indexing

I am working on a code where I need to fill the datasets with the property isProjected set to 1. There are 3 datasets - lower estimate, projected, and upper estimate. The goal is to fill the Lower Estimate and Upper Estimate with a background color of rgba ...

ngx: navigate to the specified URL once the user has been successfully logged in

I am faced with a dilemma where I must wait for my authentication server to return my token before calling my APIs. I am looking for a solution to ensure that my authState.token is not null before dispatching LoadMyStuffFromApi. I have implemented two res ...

When a user clicks on empty space in Angular 2, the page will automatically redirect

When I receive a response from the server, I want to redirect to another page. However, this process takes around 60 seconds, so in the meantime, I want to display a spinner. Once the response is received, I should be redirected to the new page. Sounds sim ...

Tips for eliminating inline CSS usage in React

Is it possible to avoid using inline CSS in React when styling an element like this? const dimensionStyles = { width: 10, height: 20 }; <div className="point-class" style={{ width: dimensionStyles.width + "px", height: ...

Trouble arises when trying to test an Angular service that relies on abstract class dependencies

Currently, I am working on a service that has a dependency on another service, which in turn relies on two abstract classes as dependencies. (ThemeConfigService -> (SettingsService -> SettingsLoader, NavigationLoader)) During testing, the failure oc ...

Fullstack is unable to locate the specified Entity name model

I am encountering an issue with my fullstack web application built using Angular and Spring Boot. When attempting to call my userEntity in the Angular service class via localhost:8080, I receive an error stating "Cannot find name 'UserEnt ...

Error encountered: ⨯ Compilation of TypeScript failed

My current project is utilizing Node.js in conjunction with TypeScript An issue has arisen during compilation within my Node.js application: E:\NodeProjects\esshop-mongodb-nodejs\node_modules\ts-node\src\index.ts:859 ret ...

Exploring the magic of Angular 4's FormBuilder: creating dynamic FormControls within a

My application enables users to choose from a dropdown menu of events, each with its own unique properties and selectable property values. This is achieved by creating a FormGroup for each event, with a FormControl for each property. Upon initialization, ...

"Encountering an error with _getHostElement in Angular Material's experimental mat-slider component. Looking for a solution

Recently, I made the switch to Angular 12 and decided to explore the new mat-slider in Angular Material Experimental. My goal was to have a range slider, but since it's not currently available in the regular Angular Material package, I wanted to stick ...

How can users create on-click buttons to activate zoom in and zoom out features in a Plotly chart?

I am currently working on an Angular application where I need to implement zoom in and zoom out functionality for a Plotly chart. While the default hoverable mode bar provides this feature, it is not suitable for our specific use case. We require user-cr ...

React Typescript can easily differentiate between various prop types by selecting either of the two types

I am working with two Typescript interfaces: type ISecond = { timeType: string secondTime: number } type IDay = { timeType: string startTime: number endTime: number } When it comes to my react function props types, ... const CountDown ...

There seems to be an issue with the Angular zone.js and zone-evergreen.js files showing an error that reads:

My Angular 11 app suddenly started showing errors across all browsers and environments (local, staging, prod) about an hour ago without any updates: Uncaught TypeError: t.getElementsByTagName is not a function at computeStackTrace.js:338 at Array.f ...

Tips for RETRIEVING a particular cookie value in Angular version 14

"I've integrated the ngx-cookie-service library in my Angular project, but I'm experiencing an issue where two different cookies are being retrieved upon login even though the session id is already set in the backend. How can I ensure that m ...

The bar chart functions perfectly on localhost but encounters issues after being hosted on Gitpage

Localhost Gitpage The bar chart was displaying correctly on localhost, but once it was hosted on Gitpage, it began to show issues. Any suggestions on how to resolve this? Repository Link: https://github.com/mzs21/bar-chart Live Preview: ...