Can i get the data from the post api in ionic?

Hello guys ,

I’m using the POST API in my ionic application. Here’s the problem, as i’m giving an image to POST API and getting some output (string value not JSON ) from that API but how can i get the value to be visible in the output in html page

Hi, first we need generate a service “ionic g provider api” this command generate a folder with the name “providers”. Inside api provider we use a post method to retrive data from your server , we need a URL and the data for example http(URL,DATA)

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Task } from '../../app/types';

/*
  Generated class for the ApiProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class ApiProvider {
  private URL:string='http://localhost:7000/api'

  constructor(public http: HttpClient) {
    console.log('Hello ApiProvider Provider');
  }

  
  createTask(task:Task):Observable<Task>{
    return this.http.post<Task>(`${this.URL}/task`,task)
  }


to use that provider we need inject in the component and call the method and pass the parameters this return an Observable and we need subscribe and get data, and assign to a variable and this variable using in HTML with curly brackets {{VariableName}}

import { ApiProvider } from '../../providers/api/api';

@Component({
  selector: 'page-add',
  templateUrl: 'add.html'
})
export class AddPage {
  task:Task
  // @ViewChild('myNav') nav:NavController;
  
  constructor(private Api:ApiProvider,private store:Store,public navCtrl: NavController ) {}

  handleSubmit(){
    this.Api.createTask(this.task).subscribe(
      datafromserver=>{
        this.task=datafromserver
      }
    )
  }
1 Like

Which library are you using for rest api? Is it returning promise or observable ?

hello guys,
can we get facebook feed of a particular hash tag in our ionic app without login authenitcation

createTask(task:Task):Observable<Task>{ return this.http.post<Task>(${this.URL}/task,task) }

in this, The variable task is an image coming from the camera the below code is for taking the picture

takePhoto()
{
const options: CameraOptions = { quality: 70, destinationType: this.camera.DestinationType.DATA_URL, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) =>{

this.myphoto = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
});
}

i need that

this.myphoto is an image to be the argument for the post api

1 Like

i’m using the observable library because the api is written in python and i’m getting the data but not the JSON

this.http.post would return an observable back. You need to subscribe to that observable and perform any actions once the response come back.

Example:
let apiObservable = this.http.post (‘url’);
apiObservable.subscribe(response => {perform some action here}, err => {log the error})

apiObservable.subscribe(response => {perform some action here}, err => {log the error})

so , in place of {perform some action here} can i return the response coming from the POST API
as

response=> {image = this.response},err => {console.log}

RTFM, particularly the bit about responseType.

Hola , variable this.myphoto it is a image , You need create a new Image to send by post method and retrieve in your server , when you send a image or a file , you need get data on the requests files , foto example in Express.js req.files is the variable that contain my files ,

Variable this.myphoto

const formData = new FormData();
formData.append(‘file’, this.myphoto, “myphotoname”);
You send form data in a post method

this.http.post(URL,formData,{heladera:new HttpHeader().set(“Content-type”,“application/x-www-form-urlencoded”)})

Espero haber ayudado en algo , saludos. :slight_smile:

Yes, that should return the response you are expecting and process accordingly.

where should i write that snippet. Is it in .ts file where i’m calling the takephoto()
i’m new to this ionic. so, please specify every point :slightly_smiling_face:

And this is my git link for the ionic application https://github.com/ksujanpaul/IonicTree

Get rid of every single new Promise in your code.

i want to get Products array using the api call in ngOnInit() of my service class.

ngOnOnit(){

this.getProducts(this.userd)

    .subscribe(data => {

 this.Products = data;

     console.log(this.Products)

     });

}

getProducts(userid) {

this.userd = userid

return this.http.post<Product>(foodUrl, {“user_id”: userid});

}

but iam getting an “empty array” of Product when iam calling addProduct() in my service
the code is below
Please anyone give me the solution.

addProduct(product) {

let added = false;

for (let p of this.cart) {

  if (p.id === product.id) {

    added = true;

    break;

  }

}

for (let i = 0; i <= this.Products.length; i++) {

  console.log(this.Products);

   console.log(product.id);

  if (product.id == this.Products[i].id) {

    this.Products[i].amount += 1;

    product.amount= this.Products[i].amount;

    break;

  }

}

if (!added) {

  this.cart.push(product);

}

this.cartItemCount.next(this.cartItemCount.value + 1);

this.getCartItemCount();

}