Home > Back-end >  Getting undefined value from service in angular 12
Getting undefined value from service in angular 12

Time:04-11

I am new to angular and I'm getting undefined value in variable after calling he service which gets the value from other component.

I am trying to send file data from one component to other using service but at the receiving component I am getting undefined value in function can someone help me with this..

1.) Sending file data as string from this component's function.

sendFile() {
    let file = this.addressDetails.value.fileSource;;
    //console.log(file);
    
    //this._sendFiles.sendFiledetails(file);
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onloadend = () => {
        resolve(reader.result)
         console.log(reader.result);
        this.stringFile = JSON.stringify(reader.result);
      };
      reader.onerror = reject;
      reader.readAsDataURL(file);
    }).then((result) => {
      this.stringFile = result;
      console.log(this.stringFile);
      
      this._sendFiles.sendFiledetails(this.stringFile);
      //this.route.navigate(['/payment']);
    });
  }

2.) This is my Service's function

export class SendFileAttachmentService {
  private _file = new Subject<any>();
  getFile$ = this._file.asObservable();
  sendFile: any;
  constructor() { }
  
  sendFiledetails(file: any) {
    //console.log(file);
    this._file.next(file);
    
    this.sendFile = file;
  }

  getFiles() {
    //console.log(this.sendFile);
    
    return this.sendFile;
  }
}

3.) This is my receiving component's function where trying to receive file data

 recieveFile() {
    this.getFiles = this._sendFile.getFiles();
    let file = this.getFiles;
    console.log("files:"   this.getFiles);
    return this.getFiles;
  }

CodePudding user response:

On the receiving component, instead of invoking the method recieveFile, you should subscribe to the getFile$ observable instead. Check out the example below:

@Component({ ... })
export class ReceivingComponent implements OnInit, OnDestroy {
  getFiles = null;
  sub: Subscription | null = null;

  constructor(private _sendFile: SendFileAttachmentService ) {}

  ngOnInit() {
    this.sub = this._sendFile.getFile$.subscribe(files => {
      // When this code gets executed it should have the value
      // emitted from the emitting component.
      this.getFiles = files;
    });
  }

  ngOnDestroy() {
    // Lets not forget to unsubscribe the subscription we made above.
    this.sub.unsubscribe();
    this.sub = null;
  }
}

Check out this StackBlitz for a full working demo.

  • Related