What is the process of retrieving a string in a method within an Ionic TypeScript file and storing it in a variable?

Having trouble returning a string to another method in an Ionic TypeScript file. Our goal is to return JSON.stringify(res) and assign it to the stringset variable. We initially tried testing by simply returning the string "hi", but even that did not work. We have attempted returning various types like any or string, but the IDE seems to disapprove of using the string type.

We need assistance figuring out how to successfully return a string from the postCall method so that it can be stored in the stringset variable.

 navNextQuestion() {
  let stringset = this.postCall("A004");
  this.navCtrl.push('QuestionPage', {
      firstPassed: stringset,
      secondPassed: "it did pass"
  });
 }


 //Below passes variable to PHP file#
 public postCall(id:string): string {
 let data=JSON.stringify({answer_id:id, type:"answer"});
 this.http.post('http://localhost/retrieve-data.php',data)
 .map(res => res.json())
 .subscribe(res => {
 alert("success "+JSON.stringify(res));

 //parses JSON response into array (uncomment below when ready)
 //this.response = JSON.stringify(res);

 return "hi";

Answer №1

Make sure to send back your post and map to that function in order to utilize the JSON Data you receive in your post.

The response data can only be accessed within the subscribe and map functions.

Recent Update

navNextQuestion() {
let stringset = this.postCall("A004").subscribe(stringset => {
this.navCtrl.push('QuestionPage', {
  firstPassed: stringset,
  secondPassed: "it did pass"
   });
 });
}

 //Passing variable to PHP file below#
 public postCall(id:string){
 let data=JSON.stringify({answer_id:id, type:"answer"});
 return this.http.post('http://localhost/retrieve-data.php',data)
   .map(res => res.json());
}

I made necessary edits to replace your code exactly.

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

Managing JSON error responses in Blob HTTP requests

One common scenario involves making HTTP calls like the following: this.http.get(`${environment.baseUrl}/api/v.1/reports/...`, { responseType: ResponseContentType.Blob }) This call returns PDF files as blobs, which we then save using FileSaver. The iss ...

Implementing multiple filters for object arrays in Angular 8

On my current project, I am interested in implementing multiple filters. The filters I want to use include price range, type, and uploaded date. For uploaded date, I have a checkbox with options for Today, Last 2 days, Last 7 days, and Any. When it come ...

Clicking on the image in Angular does not result in the comments being displayed as expected

I find it incredibly frustrating that the code snippet below is not working as intended. This particular piece of code was directly copied and pasted from an online Angular course I am currently taking. The objective of this code is to display a card view ...

Having trouble with updating to the most recent version of cordova-ios

My mobile application, developed using Ionic and Cordova, is encountering issues with the GoogleMaps plugin version 2.6.2 on iOS for the past month, while it continues to function properly on Android. I recently inherited this project from a colleague and ...

Preventing JavaScript Compilation for a Specific Folder using tsconfig: A Step-by-Step Guide

To create my own npx package, I'm currently working on converting my .ts files into .js. The purpose of the application is to generate TypeScript templates for users based on their selected options. In this app, there's a CLI called 'index.t ...

Updating the button text in Angular 7

Here's a question: <button (click)="activateMotion(1)"> <img class="emotion-icon" id="positive-icon" src="" /> </button> <button (click)="activateMotion(-1)"> <img class="emotion-icon" id="negative-icon" src="" /&g ...

Setting up Typescript error handling for next-auth getProviders configuration

I recently started learning Typescript and came across a tutorial using next-auth. However, I encountered an error while following the tutorial with Typescript when using the getProviders function. https://i.stack.imgur.com/H5LaL.png https://i.stack.imgu ...

Is there a way to use Lodash to quickly return the same value if a condition is met using the ternary operator

Is there a condensed way to do this using Lodash? (or perhaps Vanilla JS/TypeScript) var val = _.get(obj, 'value', ''); Please note that var val = obj.value || ''; is not suitable as it considers 0 and false as valid but fal ...

What is the way to retrieve an array property in a typescript interface?

Imagine a scenario with three interfaces structured as follows: registration-pivot.ts export interface RegistrationPivot { THead: RegistrationPivotRow; TBody: RegistrationPivotRow[]; } registration-pivot-row.ts export interface RegistrationPivotR ...

What could be causing the issue where I am receiving the error message that says: "Unable to access properties of undefined (reading 'index')"?

Here is the code snippet from my template: <mat-tab-group mat-align-tabs="start" (selectedTabChange)="ngOnInit($event)"> This is the ngOnInit function: ngOnInit(evt: any) { this.api.getApi().subscribe( ({tool, beuty}) => ...

Using Angular 8, you can create a reactive form that includes a custom ng-select component which has

My custom angular reactive form includes a ng-select component along with other elements. I have implemented the following code to validate the form: private validateCustForm() { this.validation.touchFormControls(this.appointmentForm); if (this.ap ...

What is the best way to ensure that the base class Resolver finishes before allowing the derived class Resolver to execute?

I have a situation where many of my resolvers (@angular/router Resolve) need to query the same data before executing their route-specific queries. To streamline this process, I want to create a resolver base class that resolves the initial data before the ...

Isolating a type as a constant in Typescript within a .js file?

Within my .js configuration files, I have a tsconfig containing the property checkJs: true. A library called Terser includes the following type options: ecma: 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 Despite setting ecma: 2017 in my configuration file ...

Leveraging React's state to enable temporary invalid numeric input handling

My current approach may be flawed, but I aim to have a parent component and a child component, where the child contains an input field for users to enter numbers. The callback function of the parent component will only be triggered for valid numbers, as ve ...

Creating an npm module using an external JavaScript API script

I am currently in the process of creating an npm package using code from this repository. In my possession is the "minified" js file called http_www.webglearth.com_v2_api.js, which is automatically downloaded by IntelliJ when the <script src=""> tag ...

Having difficulty using the Angular 6 "generic type elementref requires 2 type arguments" error message in my code

When attempting to use ElementRef, I included the following import statement: import { Component, OnInit, ElementRef, ViewChild } from '@angular/core'; I followed the examples and injected it into the constructor as shown: constructor(private ...

Configuring TypeScript for Firefox to recognize specific types such as browser.storage

As per the documentation from Mozilla, I should be able to utilize browser.storage.sync.get in my extension. However, I am encountering some challenges in getting TypeScript to recognize that I can use browser. I have attempted the following (which has wo ...

Experiencing difficulties with PrimeNg installation on Angular 12.1.4 due to an npm error

I'm facing an issue while trying to integrate PrimeNG into my project. I encountered a strange error and I'm unsure about how to resolve it. Can anyone offer some assistance? The Angular version currently installed on my machine is 12.1.4. 205-18 ...

npm installation raises concerns about unmet peer dependencies despite them being already satisfied

I recently completed an upgrade to the final release of angular 2 from rc-6. Transitioning through different beta/rc versions was smooth and without any complications. My package.json dependencies include: "dependencies": { "@angular/common": "2.0.0" ...

Personalize the Number Input Cell in ag-grid

Ag-grid field must only accept numbers. I have attempted some code that successfully works, but it adds two arrow buttons. field: "TotalQty", headerName: "TOTAL KIT QTY", editable: true, cellRenderer: params => { return '& ...