Suren Konathala
Suren Konathala

Reputation: 3597

'subscribe' undefined error when returning Observable<Object[]> from service in Angular 5?

I'm building objects new Azureblob(blob.name for each value retuned by external service and adding it to an Array new Azureblob(blob.name. Also able to return this from anonymous function return localArr.

Questions:

  1. How can we return this through the method for it to be used by the component?
  2. Also need to make it as Observable<Azureblob[] because the service takes a while to fetch the data from the server?

Model

export class Azureblob {
  blobName: string;

  constructor(private blobName1: string) {
    this.blobName = blobName1;
  }
}  

Service. Is this correct?

 import { Azureblob } from '../models/azureblob';
 ..
 export class BlobService {
   constructor() { }
   blobServiceObj: any;
   blobList: Observable<Azureblob[]> = of([]);

   getAllBlobsJS(): Observable<Azureblob[]> {
     var localArr: Azureblob[] = [];

     this.blobServiceObj = AzureStorageBlobServiceJS.createBlobService(this.connectionString);

     this.blobList = this.blobServiceObj.listBlobsSegmented('acs', null, function (error, results) {
        if (error) {
         console.log("**** Error");
        } else {
          for (var i = 0, blob; blob = results.entries[i]; i++) {
             console.log("Blob ", i, blob); /** SEE BELOW **/
             localArr.push(new Azureblob(blob.name));
           }
        }
         console.log("localArr - # of blobs returned=", localArr.length); /** SEE BELOW **/
        return localArr;
      });

      return this.blobList;
   }

The service works fine and returns result as

 Blob 0 
 BlobResult {name: "Git-Logo-1788C.png", creationTime: "Mon, 17 Sep 2018 17:57:39 GMT", lastModified: "Mon, 17 Sep 2018 17:57:39 GMT", etag: "0x8D61CC70ED10A9F", contentLength: "5684", …}

 localArr - # of blobs returned= 4

Component

blobList: Azureblob[] = [];

this.blobService.getAllBlobsJS()
  .subscribe(
    (val) => {
      console.log("..values=", val);
    });

Error i'm seeing enter image description here

Upvotes: 0

Views: 230

Answers (1)

getAllBlobsJS should return as an observable so that you can subscribe to it.

getAllBlobsJS(): Observable<Azureblob[]> { return new Observable(obs=>{ var localArr: Azureblob[] = []; this.blobServiceObj = AzureStorageBlobServiceJS.createBlobService(this.connectionString); this.blobList = this.blobServiceObj.listBlobsSegmented('acs', null, function (error, results) { if (error) { console.log("**** Error"); obs.error(); } else { for (var i = 0, blob; blob = results.entries[i]; i++) { console.log("Blob ", i, blob); /** SEE BELOW **/ localArr.push(new Azureblob(blob.name)); } } console.log("localArr - # of blobs returned=", localArr.length); /** SEE BELOW **/ return localArr; }); obs.next(this.blobList); obs.complete(); })}

Upvotes: 1

Related Questions