Sandyp Hendro
Sandyp Hendro

Reputation: 33

Angular 2 : How to display console response data?

I am not being able to do display the console response data. I dont know where I went wrong with my code. I have provided them. Will be grateful for your help.

console response

console response

account.service.ts

import { Injectable }    from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable }    from 'rxjs/Rx';
import { Account } from './account';
import { environment } from '../../../environments/environment';
import { UrlConstant } from '../../shared/constant/url-constant';

@Injectable()
export class AccountService {
 constructor(private http: Http) {
 }
 private headers = new Headers({ 'Content-Type': 'application/json' 
  });
 private authApiUri = environment['BP_AUTH_SERVER_URI'];
 listAccount(authToken: string): Observable<Account[]> {
   this.headers.set('Authorization', authToken);
   console.log(authToken, ')))))))))))))))))');
   returnthis.http.get(`${this.authApiUri}/${UrlConstant.ACCOUNT_LIST.replace('id' , '5682682637844480')}`, { headers: this.headers })
  .map(response => {
    console.log(response, 'LLLLLLLLLLLLLLL')
    let accounts: Account[] = [];
    response.json().accountList.forEach((accountResponse) => {
      let account = new Account(accountResponse.name , accountResponse.primaryEmailAddress, accountResponse.displayName);
      account.kazooAccountId = accountResponse.account_kazooAccountId;
      accounts.push(account);
    });
    return accounts;
  })
  .catch(this.handleError);
}
 private handleError(error: Response | any): Observable<any> {
   return Observable.throw(error.json());
 }
}

account.ts

export class Account {
name: string;
kazooAccountId: string;
primaryEmailAddress: string;
displayName: string;

  constructor(name: string, primaryEmailAddress: string, displayName: string) {
    this.name = name;
    this.primaryEmailAddress= primaryEmailAddress;
    this.displayName = displayName;
   }
  }

account-routing.ts

import { Routes } from '@angular/router';
import { UrlConstant } from '../../shared/constant/url-constant';
import { AccountListingComponent } from './account-listing/account-listing.component';

export const accountRoutes : Routes = [
  {
    path : UrlConstant.ACCOUNT_LISTING,
    component : AccountListingComponent
  }
];

  export  const accountRoutingComponent = [ AccountListingComponent ];

account-listing/account-listing.html

<p>
  account-listing works!
</p>
<ul>
   <li *ngFor="let account of accounts">
     {{account.name}}
     {{account.kazooAccountId}}
     {{account.displayName}}
   </li>
</ul>

account-listing/account-listing.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { CookieService } from 'angular2-cookie/services/cookies.service';

import { AppConstant } from '../../../shared/constant/app-constant';
import { Account } from '../account';
import { AccountService } from '../account.service';

@Component({
  selector: 'app-account-listing',
  templateUrl: './account-listing.component.html',
  styleUrls: ['./account-listing.component.css'],
  providers: [CookieService, AccountService]
})
export class AccountListingComponent implements OnInit {
  accounts: Account[];
  constructor(private accountService: AccountService, private router: Router, private cookieService: CookieService) {
 }

 ngOnInit() {
   this.listAccount();
 }

  listAccount() {
    const authToken: string = 
   this.cookieService.get(AppConstant.AUTH_TOKEN_COOKIE);
this.accountService.listAccount(authToken)
  .subscribe((accounts) => {
    console.log(accounts, 'KKKKKKKKKKKKKKKKKKKK')
    this.accounts = accounts;
  })
 }
}

Upvotes: 3

Views: 9920

Answers (3)

AVJT82
AVJT82

Reputation: 73357

Don't know what your expectation is, as you can see the response doesn't match the accounts. Your response is in fact similar to this:

{"id":"1","emailsFor":"emailsFor","name":"shree org one","offers":false}

Secondly, IF this would match your accounts, there is no need to iterate the response with forEach, you can just .map(res => res.json()).

Your service:

return this.http.get(...)
  .map(res => res.json())

And in your component, assign that data to a variable, here I have used simply data:

data: Object = {};

this.accountService.listAccount(authToken)
  .subscribe(data => {
    this.data = data;
  });

Then you can display the content of the response e.g like:

{{data?.id}} {{data?.emailsFor}} {{data?.name}}

This is how to display the data from your response. Your question though suggests you are looking for a different kind of response that would match your accounts. For that, you must figure out how to get the response you are looking for.

Upvotes: 1

anis programmer
anis programmer

Reputation: 999

If your data is in XML you can try this way

 HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://www.yoururl.com");

        WebResponse response = myReq.GetResponse();

        Stream responseStream = response.GetResponseStream();

        XmlTextReader reader = new XmlTextReader(responseStream);

        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Text)
                Console.WriteLine("{0}", reader.Value.Trim());
        }

        Console.ReadLine();

or you can try this way:

 WebClient client = new WebClient();
        client.DownloadStringCompleted += (sender,args) => {
            if(!args.Cancelled && args.Error == null) {
                string result = args.Result; // do something fun...
            }
        };
        client.DownloadStringAsync(new Uri("http://foo.com/bar"));

Upvotes: 0

Aravind
Aravind

Reputation: 41553

 listAccount(authToken: string): Observable<Account[]> {
   this.headers.set('Authorization', authToken);
   console.log(authToken, ')))))))))))))))))');
   returnthis.http.get(`${this.authApiUri}/${UrlConstant.ACCOUNT_LIST.replace('id' , '5682682637844480')}`, { headers: this.headers })
  ////////////////////////////////////////////////////////////////////////////////
  .do(data => {console.log(data)}) 
  //////////////////////////////////////////////////////////////////////////////////////
    .map(response => {
    console.log(response, 'LLLLLLLLLLLLLLL')
    let accounts: Account[] = [];
    response.json().accountList.forEach((accountResponse) => {
      let account = new Account(accountResponse.name , accountResponse.primaryEmailAddress, accountResponse.displayName);
      account.kazooAccountId = accountResponse.account_kazooAccountId;
      accounts.push(account);
    });
    return accounts;
  })
  .catch(this.handleError);
}

Upvotes: 0

Related Questions