Home > Enterprise >  How can I do it with just one Behaviorsubject?
How can I do it with just one Behaviorsubject?

Time:03-05

I have this code:

private _fileData$: BehaviorSubject<string> = new BehaviorSubject<string>('');
private _storageData$: BehaviorSubject<Array<string>> = new BehaviorSubject<Array<string>>([]);

    private constructor() {
        this._fileData$.subscribe({ next: (fileData: string) => this._storageData$.next(fileData.toString().split('\r\n')) });

So i have some string data in _fileData$ and I want to split it by lines so I get Array of strings, so im creating _storageData$ to put them here. It works like I want to, but how can I do it using only one BehaviorSubject?

CodePudding user response:

private _storageData$: Observable<Array<string>>;

this._storageData$ = this._fileData$
    .pipe(map((fileData) => {
        return fileData.toString().split('\r\n');
    }));

Then you can bind to it in your view:

<span>{{ _storageData$ | async }}</span>

map is an rxjs operator

  • Related