Retrieving information from BlobStorage using Service.ts and triggering the NgOnit function

Within the service.ts module, I am fetching data from Azure Blobstorage and attempting to read its contents.

service.ts

import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { JsonData } from '../models/jsondata';



import {
  BlobServiceClient,
  BlobDownloadResponseModel
} from "@azure/storage-blob";




@Injectable({
  providedIn: 'root'
})

export class JsonDataService {
  private account = environment.ACCOUNT_NAME;

  private sas = environment.SAS;
  private blobServiceClient

  constructor() { this.blobServiceClient = new BlobServiceClient(`https://${this.account}.blob.core.windows.net${this.sas}`) }


  getData(): Promise<JsonData[]> {

    return new Promise(resolve => {


      const containerName = "output2";
      const containerClient = this.blobServiceClient.getContainerClient(containerName);

      //list blobs
      let i = 1;

      async function main() {
        i = 1;
        for await (const blob of containerClient.listBlobsFlat()) {

          // console.log(`Blob ${i++}: ${blob.name}`);
          const blockBlobClient = containerClient.getBlockBlobClient(blob.name);
          console.log(blockBlobClient)
          const downloadBlockBlobResponse = await blockBlobClient.download(0);
          const download = await blobToString(await downloadBlockBlobResponse.blobBody)
          console.log(downloadBlockBlobResponse)
          //console.log("Downloaded blob content",download);
          console.log(download)
          return download

        }

      }

      //BROWSER ONLY A HELPER METHOD USED TO CONVERT A BROWSER BLOB INTO STRING
      async function blobToString(blob: Blob): Promise<string> {
        const fileReader = new FileReader();
        return new Promise((resolve, reject) => {
          fileReader.onloadend = (ev: any) => {
            JSON.parse(ev.target!.result)
            resolve(ev.target!.result);
            
          };
          fileReader.onerror = reject;


          fileReader.readAsText(blob);


        });
      }

      main().catch((err) => {
        console.error("Error running sample:", err.message);
      })

    })

  }

}

After testing this function with console.log, it's returning the correct data.

Now, I am attempting to access this function within the test.component.ts component by using ngOnit to call the function. However, it seems to only return meta data instead of the actual values returned by the getData() function.

test.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { JsonDataService } from 'src/app/services/json-data.service';
import { JsonData } from 'src/app/models/jsondata';



@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss'],
  providers: [JsonDataService]
})



export class TestComponent implements OnInit {
  @Input() title: string;
  jsondatas: Array<JsonData> = [];
  jsondata: JsonData;
  name: String;
  timestamp: number;
  value: number;

  //constructor() { }

  

  constructor(private jsonService: JsonDataService) {
  
  }

  ngOnInit(): void {
    this.jsonService.getData()
      .then(results => this.jsondatas = results);

    console.log(this.jsonService)

  }

}

The NgOnit result is as follows: console.log(this.jsonService

However, the expected output should include the defined jsondata properties such as name, timestamp, value

Answer №1

Your commitment remains unfulfilled; remember to utilize resolve(myResultJsonData) at the conclusion for it to function properly.

Here's an example:

  fetchData(): Promise<string> {
    return new Promise(resolve => {
      // Insert your code here
      resolve('myResult');
    })
  }

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

The HTTP DELETE request encountered a TypeError, stating that error.json is not a valid function

Within my Angular application, there is a feature that involves a "delete button". When this button is clicked, a confirmation popup appears asking the user if they are certain they want to proceed with the deletion. If the user confirms by clicking ' ...

Remove an element from an array within objects

Need help with removing specific items from an array within objects? If you want to delete all hobbies related to dancing, you may consider using the splice method const people = [{ id: 1, documents: [{ ...

The outcome of a promise is an undefined value

I am facing an issue where I need to access the result of my API call outside the promise, but the value I receive is always undefined. Within the OrderService : public async getOrderPrice(device: string) : Promise<any> { this.urlOrderPrice = th ...

Exploring Angular's Parsing Function ($parse)

Currently, I am working on an AngularJS component that takes a string template as input and compiles it using the following code snippet. Later, I use this compiled template to render different items: this.$parse(template); While trying to achieve someth ...

Child component responsible for closing the modalI will guide you through

A component in my project has a header with a modal window that pops up when clicked: <a (click)="open(content)" class="in">Sign in</a> <ng-template #content let-modal> <button type="button" class="close" aria-label="Close" (click)= ...

Generate a custom string to reference a JSON object containing a variable from an Angular HTML document

I am trying to generate a string within my HTML file to access data from a JSON object. HTML File <app-banner></app-banner> <section id="mail-view" class="bg-gray" > <div class="container"> <figure id="state-stats" class= ...

Error: Promises must be managed correctly

I've been working on a timer-based function that is supposed to run once a week and create almost identical copies of existing documents. However, every time I try to execute it, I encounter the error message "Promises must be handled appropriately." ...

Error: The function child.send is not defined as a valid function

Encountering an issue while attempting to build my Angular application. npm run build All tasks run smoothly on local machine and the project is successfully built. However, when trying to execute the command on the server via console (ssh), I am faced w ...

Classifying Union Types based on their distinct characteristics

There is a specific type with its own unique property (method) type Functions = { method: "connect", request: number, response: number, } | { method: "remove", request: string, response: string, } I aim to create a function that can handle inp ...

Removing HTML Tags in Ionic - A How-To Guide

After utilizing Ionic 3 to retrieve data from a WordPress API, I am encountering an issue with displaying the content on the app UI. The problem arises from the presence of HTML tags within the content being printed along with the text. While seeking solut ...

Why is the *.ngsummary.json file used?

I recently discovered AOT and ngc. When I run ngc, I notice numerous *.ngsummary.json files appearing in the src folder alongside the *.ts files. Can someone please explain their purpose? ...

Labeling src library files with namespaces

I have developed a ReactJS website that interacts with a library called analyzejs which was created in another programming language. While I am able to call functions from this library, I do not have much flexibility to modify its contents. Up until now, ...

Having trouble retrieving the file using the MS Graph API, however, it is successfully accessible through Graph Explorer

User B received an excel file shared from User A's Onedrive, whether it is in the personal folder or business OneDrive. Accessing it through regular means such as a link works fine for user B. Running the call in MS Graph Explorer produces the expect ...

Encountered an issue with Angular 8 Firebase where an error was thrown at node_modules/firebase/index.d.ts(4369, 38): TS1005 error - expecting a sem

Having some trouble setting up Firebase on my Angular 8 application. I went through the following steps: 1. Deleted my node_modules 2. Ran npm install 3. Ran npm install --save firebase @angular/fire 4. Ran npm run build Encountering this error message: ...

In TypeScript, if all the keys in an interface are optional, then not reporting an error when an unexpected field is provided

Why doesn't TypeScript report an error when an unexpected field is provided in an interface where all keys are optional? Here is the code snippet: // This is an interface which all the key is optional interface AxiosRequestConfig { url?: string; m ...

How to handle an already initialised array in Angular?

I came across an interesting demo on exporting data to Excel using Angular 12. The demo can be found at the following link: This particular example utilizes an array within the component TypeScript file. import { Component } from '@angular/core' ...

Improving Your Utilization of Angular's @input() Feature

My current dilemma involves a sub-component that requires three variables from the parent component. These three variables all stem from one object, like so: let man = {name:'John',gender:'male',age:42,birthday:'1976-6-12'} ...

How to extract component prop types in Vue 3 with typescript for reusability in other parts of your application

When you specify the props under the "props:" key of a Vue component, Vue can already automatically determine their types, which is quite convenient. However, I am wondering if there is an utility type in Vue that can be used to extract the props' ty ...

What are some ways to create a dynamic child server component?

Take a look at the following code snippet // layout.tsx export default function Layout({children}: any) { return <div> {children} </div> } // page.tsx export const dynamic = "force-dynamic"; const DynamicChild = dynamic( ...

Place the cursor at the conclusion of the text box

I am working on creating a user input form for chat messaging and I need some help. Here is the HTML-code snippet that I am currently using: HTML-code Currently, when the user presses ENTER, I retrieve the text from the textbox and save it. If the user ...