Search code examples
angularapiangular-httpclient

Angular - Getting result as "Null" from backend


I'm trying to pull datas from "http://169.38.82.132:94/GetFarmerInfo" to "http://localhost:4200/". First I need to create a token and pass the same to the above URL to get the datas to be displayed in the required format. I have created a toke using "fetchPeople()" and passed the same as "this.token" in "fetchFarmerDetails(Venktoken:string)". Everything is working fine but am getting the farmerdetails as null, please let me know if any changes has to done to get the needed results.

//people.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse ,HttpHeaders} from '@angular/common/http';


@Injectable({ providedIn: 'root' })

export class PeopleService {
  constructor(private http: HttpClient) { } 

  token:string;

  fetchPeople() {       
      let url = "http://169.38.82.132:94/token";    
      var data = "grant_type=password&username=user&password=user";
  return this.http.post( url, data,
    {headers: new HttpHeaders({
      'Accept': 'application/json',
      'Content-Type': 'application/json; charset=utf-8'
    })}  
    )
    };   

    fetchFarmerDetails(Venktoken:string) {
      console.log("Welcome");
      console.log(Venktoken);
      this.token = Venktoken;    
      console.log(this.token);
     let url = "http://169.38.82.132:94/GetFarmerInfo";     
     var data1 = "'InstanceName': 'ORISSA'";
let headers = new HttpHeaders()
.set("Authorization", 'Bearer ' + this.token)
.set('Content-Type','application/json');
     return this.http.post(url, data1, {headers:headers});     
    };

  }  

in the above code am getting the token and am passing the same to "fetchFarmerDetails(Venktoken:string)", in console the token gets displays.

app.component.ts
import { Component } from '@angular/core';
import { PeopleService } from './people.service';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  people$;
  name:string;
  Temp_token: string;
  title = 'demojsontable';
  constructor(private peopleService:PeopleService,private http:HttpClient){

  }
  fetchPeople() {
    this.peopleService.fetchPeople().subscribe((res:any)=>{      
      console.log(res);
      this.Temp_token= res.access_token;      
      console.log(this.Temp_token); 
      this.fetchFarmerDetails();     
    });
  }

  fetchFarmerDetails(){  

    this.peopleService.fetchFarmerDetails(this.Temp_token).subscribe((resp:any)=>{         
    console.log(resp);   
    this.people$ = resp.FarmerDetails;
    });
   }

}

and finally i need to display the result in tabular form for that am using the below code

app.component.html
<!--<app-datas></app-datas>-->
<button (click)="fetchPeople()">Fetch People</button>

<hr>
<table border="1">
    <thead>       
            <td>Farmer Code</td> 
            <td>Farmer Name<td>  

    </thead>
    <tbody>
    <tr *ngFor="let person of people$|async">
        <td>{{person.FarmerName}}</td> 
        <td>{{person.FarmerCode}}</td>        
    </tr>
</tbody>
</table>

First am trying to get farmername and farmer code alone. Please help me to achieve this.


Solution

  • First issue is in the file, people.service.ts,

    fetchFarmerDetails(Venktoken:string) {
         .
         .
         .
         var data1 = "'InstanceName': 'ORISSA'";
         .
         .
         return this.http.post(url, data1, {headers:headers});     
    };
    

    While you using this.http.post(), the second argument (body) which you passing is invalid, rather you should pass it as an object like,

    var data1 = {InstanceName:'ORISSA'}
    

    Next, in app.component.ts,

    change people$; to people$: any[] = [];

    Even though it works with people$;, follow the syntax for defining array types in TypeScript.

    You need to initialize the type of data for $people here..

    Also in app.component.html,

    Change <tr *ngFor="let person of people$|async"> to <tr *ngFor="let person of people$>

    Unless you are using observable array don't use async pipe..