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;
}
On the receiving component, instead of invoking the method
recieveFile
, you should subscribe to thegetFile$
observable instead. Check out the example below:Check out this StackBlitz for a full working demo.