So i have a service with the following code
@Injectable({ providedIn: 'root' })
export class FileService {
private localfiles: UploadedFile[] = [new UploadedFile('asdasd', 'sdfsdfsd', false, 1, 2, 'dsfsf')];
filesChanged = new Subject<UploadedFile[]>();
constructor() {}
setFiles(file: UploadedFile) {
this.localfiles.push(file)
console.log(this.localfiles)
this.filesChanged.next(this.localfiles.slice())
console.log('after')
}
I then have a component as follows
export class FileslistComponent implements OnInit {
files: UploadedFile[];
constructor(private fileService: FileService) { }
ngOnInit(): void {
this.files = this.fileService.getFiles();
this.fileService.filesChanged.subscribe((files: UploadedFile[])=>{
console.log('never gets here')
this.files = files;
})
}
}
When I call setFiles the array is updated as can bee seen from the console log of the array. But the console log inside the subscribe within the component is never display and the array there isn't updated.
CodePudding user response:
It seems that you're calling the setFiles
functions before initializing the component or subscribing to the filesChanged
. So, it's better in such cases to use BehaviorSubject instead of normal Subject
, which will keep the latest emitted value within its buffer to pass it to the subscribers that come after emitting the value.
P.S. If you don't want to allow the consumers of the service to emit new values to the Subject
, it's better to expose it as observable using the Subject.asObservable() function.
CodePudding user response:
this is because however subscribe
to subject
will not get the last value of it, only from now on. so it looks like your component initializes after following the method called so the subscribe
will not trigger this time.
you can use behaviorSubject
instead - this one return the last omitted value when subscribing to it.
check this out behaviorSubject