Challenges encountered when passing objects with Angular 2 promises

I am encountering a problem when using a promise to retrieve a Degree object in Angular 2. The initial return statement (not commented out) in degree.service functions correctly when paired with the uncommented implementation of getDegree() in build.component. However, upon attempting to switch to either of the commented-out implementations utilizing a promise, the object consistently returns as "undefined"

degree.service.ts

import { Injectable } from '@angular/core';

import { Degree } from '../components/degree';
import { Category } from '../components/category';
import { Course } from '../components/course';

import { SAMPLE } from '../components/mock-degree';

@Injectable()
export class DegreeService{
  getDegree(){
    return SAMPLE;
    // return Promise.resolve(SAMPLE);
    // return new Promise<Degree>(function (resolve, reject) {
    //  resolve(SAMPLE);
    // })
  }
}

build.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { SEMANTIC_COMPONENTS, SEMANTIC_DIRECTIVES } from "ng-semantic";

import { Course } from '../course';
import { Category } from '../category';
import { PaneComponent } from './pane/pane.component';
import { Degree } from '../degree';

import { DegreeService } from '../../services/degree.service';


const blank: Category = {
  name: '',
  rank: 1,
  rulestat: 'no',
  categories: [],
  courses: []
}

@Component({
    selector: 'my-build',
    directives: [SEMANTIC_COMPONENTS, SEMANTIC_DIRECTIVES, PaneComponent],
    templateUrl: `app/components/build/build.component.html`,
    providers: [DegreeService]
})



export class BuildComponent implements OnInit{
  constructor(private degreeService: DegreeService){}

  level: number = 1;
  currDeg: Degree;
  parents = [blank, blank, blank, blank];


  setLast(lst: Category){   //pass category objects, do all UI changing here
    this.level = lst.rank + 1;
    this.parents[lst.rank - 1] = lst;
  }

  getDegree(){
    //this.degreeService.getDegree().then(deg => this.currDeg = deg)
    this.currDeg = this.degreeService.getDegree();
  }

  ngOnInit(){
    this.getDegree();
  }
}

Answer №1

When using the currDeg in your template, it's important to consider that promises introduce asynchronicity into the process. This means that the corresponding object may be undefined initially, until it is set later on once the promise is resolved. Even if the promise is resolved immediately with Promise.resolve.

export class DegreeService{
  getDegree(){
    return Promise.resolve(SAMPLE);
  }
}

@Component({
  selector: 'my-app',
  providers: [DegreeService],
  templateUrl: 'src/app.html'
})
export class App {
  constructor(private degreeService:DegreeService) {
  }

  getDegree(){
    this.degreeService.getDegree().then(deg => {
      this.currDeg = deg;
      console.log('this.currDeg = ' + this.currDeg); // <------
    });
  }

  ngOnInit(){
    this.getDegree();
  }
}

For a working demonstration, refer to this plunkr: https://plnkr.co/edit/1fxE0okyMNj2JktURY4w?p=preview.

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

Angular.js reports that the custom HTTP response header is missing

Despite Chrome showing the correct POST response headers, my custom HTTP header X-Auth-Token is returning null in the callback function for the POST request. Angular.js seems to only be returning Cache-Control and Content-Type, with everything else showing ...

Having issues with C# ASP.Net autocomplete not functioning properly when using Javascript/Json post

I have been working on a c# asp.net usercontrol that requires a functional autocomplete feature. However, I am encountering an ongoing issue where the script appears to be running – with the progress bar spinning – but it consistently returns an ' ...

Gather data on webview requests and their corresponding responses

In my app, I am developing a feature that allows users to browse the web using a webview element. <webview src='user-generated'></webview> I am trying to find a way to capture all requests and responses generated during this process ...

Trouble with formatting credit card numbers in Vue.js

My payment gateway component includes a feature where selecting credit card triggers the _formatCreditCard method to format the credit card number like this: 4444 2442 4342 3434 This is the function in question: _formatCreditCard: function() { var n ...

Are there distinctions between using app.use("/", express.static) versus app.use(express.static)?

Is there a distinction between the following scenarios, assuming we have already executed app.set('thePath', thePath)? app.use('/', express.static(thePath)) app.use(express.static(thePath)) app.use(express.static(app.get('thePath ...

removing duplicate items from an array in Vue.js

I created a Pokemon App where users can add Pokemon to their 'pokedex'. The app takes a pokemon object from this.$store.state.pokemon and adds it to this.$store.state.pokedex. However, users can add the same pokemon multiple times to the pokedex, ...

Encountering an error while using $state.go function in Angular JS testing

Below is the code snippet for a Controller in Angular JS: describe('Controller: homeCtrl', function () { beforeEach(module('incident')); var homeCtrl, $state; beforeEach(inject(function ($controller, _$state_) { $state = _ ...

Why do developers opt for getServerSideProps() over a standard asynchronous function in their code?

Recently, I decided to experiment with the getServerSideProps() function. While I understand it must have its purpose, to me it seems similar in utility to a typical async function. Take for example my current task of retrieving user data using Prisma and ...

Partial View fails to render on the webpage

After submitting information from my first partial view, I attempted to load a second partial view. However, upon submission, the first partial view just refreshes and remains on the same page instead of loading the new view. Despite setting up my controll ...

Utilizing event bubbling in Angular: a comprehensive guide

When using Jquery, a single event listener was added to the <ul> element in order to listen for events on the current li by utilizing event bubbling. <ul> <li>a</li> <li>b</li> <li>c</li> <li>d< ...

Using a string array in a JSON model - a simple guide

Just starting out with Angular and having some difficulty integrating my JSON data effectively. Inside my service, I have temporary JSON data that is structured using a model to define the different types of information within it. My objective is to creat ...

Can you explain the purpose of the statement `var MyConstructor = function MyConstructor()`?

Can you explain the distinction between these two code snippets: var NodestrapGenerator = module.exports = function NodestrapGenerator() { yeoman.generators.Base.apply(this, arguments); // more code here }; and: var NodestrapGenerator = module.expor ...

`res.render when all data queries are completed``

When I make an app.get request in my server.js file, I retrieve a dataset from MongoDB and then render my page while passing the data to it. Here is an example: //page load app.get('/', (req, res) => { //find all data in test table ...

Guide to modifying the column color in Chart.js

Link to my codepen project: Check it out here let ctx = document.getElementById('myChart').getContext('2d'); let chart = new Chart(ctx, { // Type of chart being created type: 'bar', // Data for the dataset data: { ...

The dividers flicker in and out of view

I have a menu with 7 elements, where clicking on an element causes its content to appear by fading in. If another element is clicked, the current content fades out and the new content fades in. I've successfully implemented this concept for 3 of the 7 ...

NPM - Include in package.json without installation

Can a command be executed to validate that the package is a legitimate npm package, include it as a dependency in package.json, but refrain from actually installing it? This question arises from the need to utilize a specific package globally and incorpor ...

After reloading the page, Nuxt dynamic routes are displaying a 404 error

Hey there! I'm currently diving into a project that involves using nuxt js, and it's all new to me. I've set it up in spa mode without any modifications in the nuxt config file, just sticking with the default settings. Here's how I&apos ...

What is the best way to trigger a unique modal dialog for every element that is clicked on?

I simply want to click on the state and have that state's specific pop-up appear. $("path, circle").on('click', function(e) { $('#info-box').css('display', 'block'); $('#info-box').html($(this ...

Sometimes, JQuery struggles to set input values accurately

Exploring the single page app sample provided here, I have encountered some anomalies when attempting to manipulate input controls with JQuery under certain conditions. Below is the consistent HTML structure followed by the JavaScript snippets in question. ...

Syntax Error: The function `loadReposFromCache(...).error` is not defined in this building

I'm currently attempting to utilize the SyntaxHighlighter v4 plugin, but I'm facing issues with the build process! While following the guidelines provided here, an error popped up: $ ./node_modules/gulp/bin/gulp.js setup-project [10:12:20] Requ ...