Ashish_more
Ashish_more

Reputation: 55

Getting undefined value in property angular

I'm new to angular and I'm trying to get string data from shared services in my second component which is receiving value from another component. So I'm subscribing to the observable to receive the string data from service, after receiving value in the another component I'm storing the value in property as shown below, but can't access the string data stored in property outside of the function..

Please can somebody can guide me with this issue..

This is the function where I am subscribing to the observable

 ngAfterViewInit(): void {
    this.recieveFiles();
    this.sendAttachment();
  }

  recieveFiles(){
    this._sendFile.getFile$.subscribe(files => {    
      // When this code gets executed it should have the value
      // emitted from the emitting component.
      this.getFiles = files;
       console.log("File:" + this.getFiles);   <- **Here I am getting the string data in console**
      return this.getFiles;
   
    });   
  }

x:any;
  sendAttachment(){
    let y = this.getFiles;
    console.log("String Files:" + y);  **This where I am getting undefined as shown in Screenshot**
  }

here are the screenshots enter image description here

enter image description here

Upvotes: 1

Views: 1275

Answers (2)

Tu Nguyen
Tu Nguyen

Reputation: 174

Here's your problem:

this.recieveFiles(); <-- Begins to receive the file
this.sendAttachment(); <-- Before the file is received, Angular executes this

The fix is to wait for the actual file to load before calling sendAttachment(), meaning you can do this.sendAttachment() inside the subscription:

    this._sendFile.getFile$.subscribe(files => {    
      this.getFiles = files;
      this.sendAttachment(); <-- Here's your fix.
    });  

Upvotes: 1

Devashish Sarmah
Devashish Sarmah

Reputation: 49

return this.getFiles; is unnecessary. Instead of that line, put this.sendAttachment();

In your ngAfterViewInit, there are two methods that are being invoked. recieveFiles -> Which runs a subscription and gets the files. sendAttachment -> Which does something with the files.

In your implementation the sendAttachment runs before recieveFiles subscription gets the files. hence it was showing as undefined.

Upvotes: 0

Related Questions