Showing console response data in Angular 2: A comprehensive guide

I seem to be having trouble displaying the console response data correctly. I've checked my code multiple times but can't figure out where the issue lies. Any assistance or guidance on this matter would be greatly appreciated.

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;
  })
 }
}

Answer №1

Uncertain about your expectations because the response doesn't align with the accounts. Your current response resembles:

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

In case this is the correct match for your accounts, there's no need to loop through the response using forEach, you can simply use .map(res => res.json()).

Your service:

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

In your component, assign the data to a variable like so - here I've named it data:

data: Object = {};

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

You can then display the content of the response as follows:

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

This is how you can show the data from your response. However, it seems like you may be seeking a different type of response that corresponds with your accounts. If that's the case, you'll need to determine how to obtain the desired response.

Answer №2

 fetchAccountListFromServer(token: string): Observable<Account[]> {
   this.headers.set('Authorization', token);
   console.log(token, ')))))))))))))))))');
   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);
}

Answer №3

If you have XML data, here are two different approaches you can try:

 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();

Alternatively, you could also attempt this method:

 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"));

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

Exploring dynamic data with Highcharts geomaps

API is being called to display data in the chartOptions. However, I am encountering an issue trying to pass it through this.letsTry. I am unsure where I am making a mistake. [data-local.component.html] <highcharts-chart id="container" [Highch ...

I need to adjust the print layout so that the material extends beyond the confines of an A4 page

I created a chalan format with 3 copies, however only 2 of them are printing correctly on the same page. The third copy is not displaying properly. Take a look at this screenshot: ...

Difficulty loading images in Angular 2 after deploying the dist folder (renamed to "myapp") to the tomcat webapp directory

When I pass the relative path and use the command below to build, I encounter a problem! ng build --prod --aot --base-href /myapp/ The issue arises with a 404 Resource not found error. bkgraph.jpeg:1 GET http://localhost:8081/assets/bkgraph.jpeg 404 () ...

Typescript is throwing an error stating that the module does not have any exported

Currently, I am using TypeScript for a personal project and attempting to import a function from a library called Solid Client JS. The issue arises when I only include the following line in my single `file.ts`: import { getFile } from '@inrupt/solid- ...

timer-based user session expiration

Currently, the app I'm developing has a system where a session is created with a 15-minute expiration time once a user interacts with a form. This session is managed server-side. If the user remains idle for 15 minutes, the server returns a 404 erro ...

The third-party SDK no longer includes names and autocomplete functionality

I am encountering an issue where my previously working SDK environment has suddenly stopped recognizing names and providing autocomplete. I am wondering what could have caused this problem - is it related to SDK maintenance or is the SDK offline? The SDK ...

Tips for accessing the callback parameter in the validateFields method of antd form

Here is a question about typing the callback parameters for form.validateFields in Ant Design when using the Form HOC. // App.tsx import { FormComponentProps } from 'antd/lib/form'; interface IProps extends FormComponentProps { ... } class App ...

Struggling to render the template inside a .vue file in a Vue.js + TypeScript project?

Is anyone familiar with setting up a Vue TS based project? I have encountered an issue where the template data is not being rendered in the browser's DOM. The project structure can be found in this repository: https://github.com/AndrewBogdanovTSS/typ ...

Sorting through a collection of objects using various criteria in typeScript

Hello team, I have an array of objects that looks like this: data = [ { name: "Pork", category: "Food", subcategory: "Meat" }, { name: "Pepper", category: "Food", subcategory: "Vegetables" }, ...

Angular - Loading images on the fly

After scouring numerous resources, I couldn't find a resolution to my issue. For your information, I am utilizing ASP.net Core 2.0's default angular project In the process of developing an Angular application, I am faced with the challenge of ...

Angular6 - Utilizing service calls as references in child components

I'm currently working on a unique custom select component that retrieves data from a service call initiated by its parent component. In cases where the initial service call fails, I need to implement a retry function within the select component itself ...

Is there a way to specify the login response details when making an Angular API request?

I am currently using Angular to connect to my backend login service. However, I am facing an issue with setting the popup message when the username or password is incorrect. I want to display the detailed message from the API on my login page when any erro ...

Angular's HttpClient is stating that the property '.shareReplay' is not recognized on the type 'Observable'

Excuse me for asking what may seem like a basic question. I'm currently following a tutorial at this link: I have created the Service as shown in the tutorial, but I am getting an error that says Property '.shareReplay' does not exist on ty ...

Guide to building a nested dropdown navigation in Angular 12 with the power of Bootstrap 5

I am looking to implement a multilevel dropdown feature in my Angular 12 project with Bootstrap 5. Can someone please guide me on how to achieve this? For reference, you can view an example here. Thank you in advance! ...

Determining the parent type in Typescript by inferring it from a nested member

Typescript has the ability to infer the type of a value based on queries made within if statements. For instance, the type of one member of an object can be deduced based on another: type ChildType = 'a' | 'b'; type Child<T extends ...

What is the best way to simulate a global variable for Unit Testing using Jasmine?

I'm currently facing a challenge while testing a service within my Angular application. Specifically, I am unsure of how to mock a variable that is declared outside of my method. Here is an excerpt from my service: export class MyService { priva ...

WebStorm/JetBrains alert: TypeScript identifies lack of native functionality in arrays

Update 3: I've decided to move this important information to the top of the post as it directly relates to the question at hand. Following a suggestion from AlexWayne, I simplified the code sample and encountered the same issue. Surprisingly, compilin ...

Unable to communicate with the console

Exploring Angular for the first time and attempting to set up a reactive form. Here's a glimpse of my HTML and TypeScript codes: <form [formGroup]="signupForm" (ngSubmit)="onSubmit()"> <div class="form-group"> <label for="email"& ...

Guide on accessing and displaying images stored in an S3 bucket on Angular

I am working on developing an image slideshow viewer using Angular 8. The images I want to use are stored in the S3 browser. Can anyone advise me on the best way to retrieve all the images from the S3 bucket for integration into my Angular 8 project? ...

Error Message: "Unable to locate module component - Storybook with TypeScript"

I'm encountering an issue when running Storybook, specifically this error message: ERROR in ./components/atoms/input/input.tsx 14:0-40 Module not found: Error: Can't resolve 'react-tagsinput' in '...' To provide some context ...