Using Angular to show information in a textarea box from a service

Recently, I picked up Angular and worked on the tour-of-heroes app. Currently, I'm facing a challenge in displaying a set of steps in a textarea based on the selected hero. The idea is that when hero1 is selected, it should show step 1, and upon clicking "next", it should display step 2. Unfortunately, I'm encountering an issue where it displays "[object Promise]" instead of the desired step. Any assistance in solving this problem would be greatly appreciated.

calibration-detail.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { Hero } from '../hero.class';
import { Step } from '../step.class';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import { InMemoryDataService } from '../in-memory-data.service';
import { HeroService } from '../hero.service';
import { StepService } from '../step.service';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';

@Component({
moduleId: module.id,
selector: 'app-calibration-detail',
templateUrl: './calibration-detail.component.html',
styleUrls: ['./calibration-detail.component.css']
})

export class CalibrationDetailComponent implements OnInit {

@Input()
hero: Hero;
step: Step;

private mainStepText: String = "Main window text"; //It doesnt want to accept this.hero.id
private statusStepText: String = "Status window text";

constructor(
 private heroService: HeroService,
 private stepService: StepService,
 private route: ActivatedRoute,
 private location: Location,
 private http: Http,
 //private memoryService: InMemoryDataService
) { }


ngOnInit(): void {
 this.route.params
   .switchMap((params: Params) => this.heroService.getHero(+params['id']))
   .subscribe(hero => this.hero = hero);

 this.route.params
   .switchMap((params: Params) => this.stepService.getStep(+params['id']))
   .subscribe(step => this.step = step);
}

goBack(): void {
this.location.back();
}

save(): void {
this.heroService.update(this.hero)
  .then(() => this.goBack());
}
next(): void {
this.mainStepText = this.stepService.getStep(this.step.id).toString();
}
}

steps.components.ts

import { Component, OnInit } from '@angular/core';
import { Step } from '../step.class';
import { StepService } from '../step.service';
import { Router } from '@angular/router';

@Component({
moduleId: module.id,
selector: 'app-steps',
templateUrl: './steps.component.html',
styleUrls: ['./steps.component.css']
})
export class StepsComponent implements OnInit {
steps: Step[];
selectedStep: Step;

constructor(
private router: Router,
private stepService: StepService) 
{ }

getSteps(): void {
this.stepService.getSteps().then(steps => this.steps = steps);
}

ngOnInit(): void {
this.getSteps();
}

onSelect(step: Step): void {
this.selectedStep = step;
}
gotoDetail(): void {
this.router.navigate(['/detail', this.selectedStep.id]);
}
}

step.service.ts

import { Injectable }    from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Step } from './step.class';

@Injectable()
export class StepService {

private headers = new Headers({'Content-Type': 'application/json'});
private stepsUrl = 'api/steps';  // URL to web api

constructor(private http: Http) { }

getSteps(): Promise<Step[]> {
return this.http.get(this.stepsUrl)
           .toPromise()
           .then(response => response.json().data as Step[])
           .catch(this.handleError);
}

getStep(id: number): Promise<Step> {
const url = `${this.stepsUrl}/${id}`;
return this.http.get(url)
  .toPromise()
  .then(response => response.json().data as Step)
  .catch(this.handleError);
}

private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
} 
}

calibration-detail-component.html

<div class="grid grid-pad">
<div class="col-1-2">
<div *ngIf="hero">
  <h2 class="labelName">{{hero.name}} details!</h2>
</div>
<div *ngIf="step">
  <div class="mainWindow">
    <textarea readonly="textareaEdit" ng-model="textareaValue" [(ngModel)]="mainStepText"></textarea>
 </div>
  <div class="status">
    <textarea readonly="textareaEdit2" style="background-color: #7B797B;" ng-model="textareaValue" [(ngModel)]="statusStepText"></textarea>
  </div>
 </div> 
 </div>
 <div class="col-1-2">
  <div class="container">
    <div class="pull-right">
        <button style ="min-height: 70px" (click)="empty1()">Empty</button>
        <button style ="min-height: 70px" (click)="save()">Ok</button>
        <button style ="min-height: 70px" (click)="next()">Next</button>
        <button style ="min-height: 70px" (click)="goBack()">Back</button>
        <button style ="min-height: 70px" (click)="empty3()">Empty</button>
    </div>
  </div>
  </div>
  </div>

Answer №1

There is an issue with the step service call in your code:

this.mainStepText = this.stepService.getStep(this.step.id).toString();

When calling getStep, it returns a Promise object. Using .toString() on it will return "[Object Promise]". To fix this, you should replace it with the following:

Update

this.stepService.getStep(this.step.id).then(data => (this.mainStepText = data.name));

By using this approach, you can handle the returned Promise correctly and assign the data it contains to your local variable.

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

Encountered an optimization error during the docker build process with Ng build

Encountering an error while trying to build an Angular app in docker, specifically when running npm run build: #11 1.106 > ng build #11 1.106 #11 4.769 - Generating browser application bundles (phase: setup)... #11 32.23 ✔ Browser application bundle g ...

Angular now displays an unsupported Internet Explorer version message instead of showing a white screen

I am responsible for developing new features and maintaining an Angular application (version 8.3.4). Initially, we wanted the application to be compatible with all versions of Internet Explorer, but that turned out to be impractical. While the application ...

How can you indicate that a function in TypeScript is expected to throw an error?

An error occurs when trying to compile the following code: "a function whose declared type is neither void nor any must return a value or consist of a single throw statement." Is there a way to indicate to the compiler that _notImplemented throws an excep ...

Solving automatically generated TypeScript MongoDB types for GraphQL results

Utilizing the typescript-mongodb plugin along with graphql-codegen to automatically generate Typescript types enables easy data retrieval from MongoDB and GraphQL output via Node. The initial input schema in GraphQL format appears as follows: type User @ ...

To enhance VS IntelliSense and type checking in react-intl's FormattedMessage component, assign an id that aligns with a custom TypeScript interface

Due to the limitations of react-localization in terms of date and number formats, as well as its heavy reliance on a single developer, our team made the decision to transition to react-intl for a more stable long-term solution. Check out the contributors ...

The transition to Angular 7 has caused complications with the Octopus deployment process

Situation Working on an Angular 4.3 project that is built using Jenkins Utilizing "octo.exe pack ..." step to package output into a NuGet package Using Octopus for deployment to IIS Issue at Hand After upgrading the project to Angular 7, encountering ...

The 'status' attribute is not found within the 'User' data type

Currently, I am invested in a personal project using Angular 6 for the client side and Laravel 5.6 for my API. Despite successful testing of the API endpoints with Postman, I find myself struggling to comprehend the behavior of my auth service. To provide ...

Unable to save a dynamic FormArray within a FormGroup

My FormGroup consists of three FormControl fields and one FormArray field, as shown in the figure below. I need to collect the manager's name from the user. When the add button is clicked, the manager details should be displayed in a table. In the tab ...

Utilizing [src] syntax in Angular 2 and webpack to efficiently import images

When attempting to import an image in my Angular 2 application, I encountered an issue. I tried using the following code: <img *ngIf="person.status" [src]="{{IMAGE_URL}}" width="20" height="20" /> However, the problem arose when using the [src] tag ...

Adjust puppeteer window dimensions when running in non-headless mode (not viewport)

Is there a way to adjust the browser window size to match the viewport size in Chrome(ium)? When only setting the viewport, the browser can look awkward if it is not running headfully and I want to visually monitor what's happening within the browser ...

Tips for subscribing to an Angular Unit Test:

In the process of writing test cases for a component, I first tackled a basic test case to ensure smooth functionality. Initially, I faced Dependency Injection errors and managed to resolve them. The current challenge I am encountering involves mocking API ...

Angular searchbar issue: Unable to assign parameter of type 'unknown' to parameter of type 'string'

I've been working on an Angular app to fetch data from an API successfully. However, I'm currently facing a challenge while implementing a search function in my component.ts file. Here is the entire service code: import { Injectable } from &apos ...

Retrieve a static property from a specific type

I've encountered a dilemma with the code snippet below: class Action { public static DEPENDENCIES: (typeof Action)[] = []; public static MIN_USES: number | null = null; public static MAX_USES: number | null = null; } class SomeAction ext ...

Combining HTML with multiple .ts files in Angular

I've been dedicating time to enhancing an Angular application, particularly a sophisticated table with intricate styling and functionality. Within my component file, there is a whopping 2k lines of code that includes functions for text formatting, ta ...

Using Angular to transfer a function to a directive

Looking to pass the (scroll) method to a directive, I initially had it declared like this: <div class="table-responsive" pyb-fixed-table #container> After modifying it to include the method reference: <div class="table-responsive" (scroll)="onS ...

The "isActive" value does not share any properties with the type 'Properties<string | number, string & {}>'. This issue was encountered while using React with TypeScript

I'm attempting to include the isActive parameter inside NavLink of react-router-dom version 5, but I'm encountering two errors. The type '({ isActive }: { isActive: any; }) => { color: string; background: string; }' does not have an ...

What is the process for adding submitted data to an already-existing local JSON file?

I have a new Angular assignment that requires me to push form data into an existing JSON file locally. The task is to develop an Angular application where users can create new tasks and view them on a separate page. Initially, I attempted using http.post ...

Creating a dynamic navigation bar that adjusts to changing content requires careful planning and implementation

Struggling with achieving my visual mockup while designing a webpage: Check out my web design mockup Currently focusing on section 2 of the page. Using Angular 5, Bootstrap 3, and ngx-bootstrap library to integrate Bootstrap components into Angular. Here ...

Vue 3 Composable console error: Unable to access properties of undefined (specifically 'isError') due to TypeError

I recently developed a Vue 3 / TypeScript Composable for uploading images to Firebase storage. The code snippet below illustrates the structure of the ImageUpload interface: interface ImageUpload { uploadTask?: UploadTask; downloadURL?: string; progr ...

Harness the power of the Node.js Path module in conjunction with Angular 6

I'm currently facing an issue with utilizing the Path module in my Angular 6 project. After some research, I came across a helpful post detailing a potential solution: https://gist.github.com/niespodd/1fa82da6f8c901d1c33d2fcbb762947d The remedy inv ...