Exploring methods to iterate through individual models in an array within an Angular Component

I am in need of calling a web service by providing inputs and using POST method. The response from the service will be a JSON array consisting of objects. My goal is to gather these objects into an Angular Array of Objects and present them on the webpage.

However, instead of displaying the actual values of the objects, the key/values of "Subscribe" are being printed. The val within http.post does display the correct values. I am uncertain if an array of Azureblob objects is being created with

return this.http.post<Azureblob[]>(this.serverUrl...
.

Any assistance on this matter would be greatly appreciated.

https://i.sstatic.net/c2ibT.png

model

export class Azureblob {
  blobName: string;
  blobURL: string;
  blboMimeType: string;
}

service

getAllBlobs() {
const headers = new HttpHeaders({
  'Content-Type': 'application/json',
  'Accept' : 'application/json'
});

return this.http.post<Azureblob[]>(this.serverUrl,
  JSON.stringify({
    "acountName": "abc",
    "acountKey": "def",
    "container":"ghi",
  }),{headers: headers}).subscribe(
  (val) => {
    console.log("POST call successful value returned in body",
      val);
  },
  response => {
    console.log("POST call in error", response);
  },
  () => {
    console.log("The POST observable is now completed.");
  });
}

pipe

@Pipe({
  name: 'keys'
})
export class KeysPipe implements PipeTransform {
   transform(value: {}): string[] {
     if (!value) {
       return [];
     }
     return Object.keys(value);
   }
}

component

blobsList : any;
constructor(private azureblobService : AzureblobService) { }
ngOnInit() {
  this.getAllBlobs();
}

getAllBlobs() : void {
  this.blobsList = this.azureblobService.getAllBlobs();
}

component html

<div>
   <ul>
     <li *ngFor="let key of blobsList | keys">
      {{key}}
     </li>
   </ul>
</div>

Answer №1

It appears that your code is returning an observable. It is recommended to use the subscribe operator in the component rather than the service.

In Service:

getAllBlobs() {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Accept' : 'application/json'
    });

    return this.http.post<Azureblob[]>(this.serverUrl,
      JSON.stringify({
        "acountName": "abc",
        "acountKey": "def",
        "container":"ghi",
      }),{headers: headers});
}

In Component:

blobsList : any;
constructor(private azureblobService : AzureblobService) { }
ngOnInit() {
   this.getAllBlobs();
}

getAllBlobs() : void {
  this.azureblobService.getAllBlobs()
  .subscribe(
      (val) => {
        console.log("POST call successful value returned in body",
          val);
        this.blobsList = val; //<====== Set value here
      },
      response => {
        console.log("POST call in error", response);
      },
      () => {
        console.log("The POST observable is now completed.");
      });
}

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

Is there a way to maintain values in a POST request when redirecting from HTTP to HTTPS on SecureConnection?

Within my project, there is an .ashx page that receives POST requests from external sources and retrieves a string variable using the following code: string infoPost = httpRequest["infoPost"].ToString(); This code functions flawlessly when running locall ...

Setting up Angular Universal on an already existing Angular 2 application with the help of the CLI

Encountering obstacles while trying to integrate the universal CLI into an existing Angular 2 application by following the guidelines provided in this link: During the initial command to install angular-universal: npm install body-parser angular2-univers ...

What is the best way to incorporate an external .css file into my Angular project by referencing its URL?

I'm managing a collection of CSS files online and I need to incorporate each one into my project based on its specific requirements. One component in particular is connected to different numerical IDs in the router. I am looking for a way to dynamica ...

Node modules are incapable of being installed within node packages

Whenever I use the ng serve command in my terminal, an error pops up: 10% building 3/3 modules 0 activei 「wds」: Project is running at http://localhost:4200/webpack-dev-server/ i 「wds」: webpack output is served from / i 「wds」: 404s will fall ...

NextJS is currently unable to identify and interpret TypeScript files

I am looking to build my website using TypeScript instead of JavaScript. I followed the NextJS official guide for installing TS from scratch, but when I execute npm run dev, a 404 Error page greets me. Okay, below is my tsconfig.json: { "compilerOption ...

What are the steps to fix a "Cannot read property" error?

Below is a code snippet that is causing an error in the console. This function is part of the service in my Angular application. lastEmployeeID() //code block with error { let temp= this._http.get(this._employeesUrl).subscribe((employees:any ...

Error in Angular 6: Unable to access the 'length' property of an undefined variable

Encountering a peculiar issue here. I am using @Input to send data from the parent component to the child component, and even though I can retrieve the correct value in ngOnInit, I still receive an error message stating that the value is undefined. The dat ...

Is it possible to have code highlighting and intellisense features while typing within backticks in Visual Studio Code?

I am looking for a way to enable code highlighting and IntelliSense within backticks (``) in a .ts file in Visual Code. For example: let html =`<div><span>Hello</span></div>`; If you have experience with this feature in Atom or ar ...

What can we achieve using typename and nested types in a Typescript generic function?

I've been exposed to numerous tricks, but I seem to be struggling with this particular puzzle; therefore, any assistance from someone with more experience in TS would be greatly appreciated. My subscribe() function requires: Message type in the form ...

Creating a dynamic list from an array of strings in Angular: A step-by-step guide

Within my .ts component file, I have declared a variable called campaignList as an array of strings. campaignList: string[] I am dynamically populating this list programmatically. In the corresponding HTML file, I have set up a table structure with heade ...

The information is failing to display properly within the mat-menu

Recently, I've been working on creating a navbar that includes a submenu. Even though the navigation bar data is loading properly, I am facing some issues with the submenu functionality. As a beginner in this area, I would appreciate any help or guida ...

Unable to retrieve the user information using the UID of the current user in Ionic 3

Attempting to retrieve the username of a user by utilizing the current user's UID. The UID is saved in both Firebase database and authentication. this.userid=firebase.auth().currentUser.uid; this.username=firebase.database().ref('Users/'+ ...

Angular navigation did not work as expected

Created a basic webpage using Angular CLI version 8.3. The issue is as follows: For example: www.domainname.com is working fine. www.domainname.com/basicprinciples will work if visited through the main page, but it does not work when directly visiting w ...

Unusual Type Inference in Typescript {} when Evaluating Null or Undefined

Upon upgrading from typescript 4.9.3 to 5.0.2, we encountered an error when asserting types. Can someone explain why the function "wontWorking" is not functioning correctly? I expected this function to infer v as Record<string, any>, but instead it ...

Error: Serialization of circular structure to JSON not possible in Next.js

I am currently working on creating an API in Next.js to add data into a MySQL database. The issue I am facing is related to a circular reference, but pinpointing it has proven to be challenging. It's worth mentioning that Axios is also being utilized ...

What is the best way to update my list after deleting an item using promises?

I am facing an issue in my Angular application where I need to update a list after deleting an item, but I am unsure about how to achieve this using promises. delete(id: any) { this.missionService.deleteMission(id); // .then((res) => { // ...

The error message states that the property 'id' is not found on the 'User' type when using Passport and Typescript

When I try to access req.user.id while using PassportJS in Express with Typescript, I encounter the following error: Property 'id' does not exist on type 'User'.ts(2339) Upon logging req.user to the console, the id property is clearly ...

Create a d.ts file for Vue components that are written using Typescript

As a newcomer to Vue, I am eager to dive into creating components and publishing packages to NPM. My plan is to develop Vue (typescript) + Vuetify reusable components that can be easily installed from NPM into any of my projects. While I have successfully ...

Typescript feature: Configuring BaseUrl with nested directories

When utilizing the 'baseUrl' property along with the 'paths' property in this manner: "baseUrl": "./src", "paths": { "app-component": [ "app/app.component"], "test-component": [ "app/test/test.component" ] } the compilation proces ...

Develop unique web components and distribute them across various frameworks

Currently, I am working on two projects that utilize Angular and React. I have noticed that certain components are duplicated in both projects. To streamline this process, I am considering creating a company library where I can develop custom components on ...