通过 Service.ts 从 Blob 存储中获取数据并调用函数 NgOninit

Fetching data from BlobStorage via Service.ts and call the function NgOnit

在 service.ts 模块中,我从 Azure Blobstorage 检索数据并想要读取内容。

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

    })

  }

}

我用 console.log 测试了这个函数,它 returns 正确的数据。

现在我想通过 test.component.ts 组件访问这个函数,我使用 ngOnit 调用这个函数,但不知何故它只是 returns 元数据而不是通过调用 getData( ) 函数。

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)

  }

}

这是 NgOnit 的结果: console.log(this.jsonService

但我期望的是定义的 jsondata 就像 name, timestamp, value

你的承诺永远不会解决,它需要在最后调用 resolve(myResultJsonDatas) 才能工作

示例如下:

  getData(): Promise<string> {
    return new Promise(resolve => {
      // Some code
      resolve('myResult');
    })
  }