I have a problem trying to pass values into my subject and subscribing to it from another component. Here is my code that is supposed to pass my value into an observable.
private pdfLink = new Subject<string>();
pdfLinkCast = this.pdfLink.asObservable();
getPdfById(id: string): void {
this.httpClient.get<any>(this.apiUrl + id + '/pdf', this.httpOptions).subscribe((pdf) => {
// this prints
console.log(pdf);
// not sure if this is working as expected
this.pdfLink.next(pdf.url);
});
}
In my component I subscribe to it on ngOnInit as follows:
ngOnInit() {
this.subscription.add(this.someService.pdfLinkCast.subscribe((pdf) => {
// these do not print for some reason
console.log('hello world');
console.log(pdf);
}));
}
Related
I am trying to get my observable to update automatically during pagination.
Only Page Trigger
When load() is called, the page observable gets triggered, but the subscription observable does not get triggered when it is updated...
pageSub = new BehaviorSubject<number>(1);
page = 1;
// in constructor...
this.posts = this.pageSub
.pipe(
mergeMap((page: number) => this.urql
.subscription(this.GET_POSTS,
{
first: this.ITEMS.toString(),
offset: (this.ITEMS * (page - 1)).toString()
}
)
),
scan((acc, value) => [...acc, ...value]),
);
// called from button
load() {
this.page += 1;
this.pageSub.next(this.page);
}
Only Subscription Trigger
Here a subscription change does get triggered, but when load() is called, a page change does not get triggered...
this.posts = combineLatest([this.pageSub, this.urql
.subscription(this.GET_POSTS,
{
first: this.ITEMS.toString(),
offset: (this.ITEMS * (this.page - 1)).toString()
}
)]).pipe(
map((arr: any[]) => arr[1])
);
Surely, there is a way so that the Observable gets updated with a page change and with a subscription change?
I should add that resetting the variable declaration this.posts does not work, as it refreshed the page and is not intended behavior.
Any ideas?
Thanks,
J
Got it:
mainStream: BehaviorSubject<Observable<any>>;
posts!: Observable<any>;
constructor(private urql: UrqlModule) {
this.mainStream = new BehaviorSubject<Observable<any>>(this.getPosts());
this.posts = this.mainStream.pipe(mergeAll());
}
async load() {
this.page += 1;
this.mainStream.next(this.combine(this.mainStream.value, this.getPosts()));
}
getPosts() {
return this.urql.subscription(this.GET_POSTS,
{
first: this.ITEMS.toString(),
offset: (this.ITEMS * (this.page - 1)).toString()
}
)
}
combine(o: Observable<any>, o2: Observable<any>) {
return combineLatest([o, o2]).pipe(
map((arr: any) => arr.reduce((acc: any, cur: any) => acc.concat(cur)))
);
}
Why does this function only work once? I click a button to call the next() on the Subject queue which works but if I click the other button it doesn't work.
getData(text): Observable<string> {
const timer$ = timer(2000);
const observable = new Observable<string>(observer => {
timer$.pipe(
map(() => {
observer.next('http response ' + text);
})
).subscribe();
});
return observable;
}
I setup a Subject and use next() which should make the observable emit data.
queue = new Subject();
streamA$: Observable<string>;
streamB$: Observable<string>;
images$: Observable<string>;
constructor(private timerService: TimerService) {
}
ngOnInit() {
this.streamA$ = this.timerService.getData('a');
this.streamB$ = this.timerService.getData('b');
this.images$ = this.queue.pipe(concatMap((data: string) => data));
}
clickA() {
this.queue.next(this.streamA$);
}
clickB() {
this.queue.next(this.streamB$);
}
Template:
<button (click)="clickA()">Click A</button>
<button (click)="clickB()">Click B</button>
<div>{{images$ | async}}</div>
https://stackblitz.com/edit/angular-subject-queue
You're using concatMap(). This emits all the events emitted from the first observable emitted by the subject, then all the events emitted by the second observable emitted by the subject.
But the first observable never completes, so there's no way for the second observable to ever emit anything.
If you want the observable returned by the service to emit once after 2 seconds then complete, all you need is
return timer(2000).pipe(
map(() => 'http response ' + text)
);
I am working on displaying the details of event clicked. I have stored all the events inside an array.
When the user clicks on the event then its id is passed which checks inside the array and it passes the result into service.
showDetail(id){
let obj = this.events;
let newArr = Object.values(obj);
let result = newArr.filter(function(el) {
return el["id"] == id;
});
this.articleService.sendMessage(result);
let url = `/article/${id}`;
this.router.navigate([url]);
}
service
private detailSubject = new Subject<any>();
sendMessage(formData: any) {
this.detailSubject.next({formData});
}
getMessage(): Observable<any> {
return this.detailSubject.asObservable();
}
Now in my article/id page.
I am not being able to retrieve this passed array.
I have following code
ngOnInit() {
this.articleService.getMessage().subscribe(
res => {
this.loadArticleDetail(res["formData"]);
},
error => {
console.log("Error loading data");
}
);
}
this.articleService.sendMessage(result); // <-- Subject.next()
let url = `/article/${id}`;
this.router.navigate([url]); // <-- Subject.subscribe() after Subject.next(), so value already emitted
You already added BehaviorSubject tag. So use it. Also, getMessage(): Observable<any> { doesnt do anything except returns Observable. Feels redundant:
private detailSubject = new BehaviorSubject<any>(null);
message$ = this.detailSubject.asObservable();
sendMessage(formData: any) {
this.detailSubject.next({formData});
}
And
ngOnInit() {
this.articleService.message$.subscribe(...
I was trying to return filter function but return doesn't seem to work with callbacks. Here this.store.let(getIsPersonalized$) is an observable emitting boolean values and this.store.let(getPlayerSearchResults$) is an observable emiting objects of video class.
How do I run this synchronously, can I avoid asynchronus callback altogether given that I can't modify the observables received from store.
isPersonalized$ = this.store.let(getIsPersonalized$);
videos$ = this.store.let(getPlayerSearchResults$)
.map((vids) => this.myFilter(vids));
myFilter(vids) {
this.isPersonalized$.subscribe((x){
if(x){
return this.fileterX(vids);//Return from here
}
else {
return this.filterY(vids);//Or Return from here
}
});
}
fileterX(vids) {
return vids.filter((vid) => vids.views>100;);
}
fileterY(vids) {
return vids.filter((vid) => vids.views<20;);
}
I got it working this way, you don't need myFilter(vids) at all if you can get the branching out on isPersonalized$'s subscribe. Here is the updated code.
this.store.let(getIsPersonalized$);
videos$: Observable<any>;
ngOnInit() {
this.isPersonalized$.subscribe((x) => {
if (x) {
this.videos$ = this.store.let(getPlayerSearchResults$)
.map((vids) => this. fileterX(vids));
} else {
this.videos$ = this.store.let(getPlayerSearchResults$)
.map((vids) => this. fileterY(vids));
}
});
}
fileterX(vids) {
return vids.filter((vid) => vids.views>100;);
}
fileterY(vids) {
return vids.filter((vid) => vids.views<20;);
}
It looks like you want to evaluate the latest value of isPersonalized$ within the map function, i'd do that via withLatestFrom (Example: The first one toggles true/false every 5s, the second emits an increasing number every 1s):
const isPersonalized$ = Rx.Observable.interval(5000)
.map(value => value % 2 === 0);
const getPlayerSearchResults$ = Rx.Observable.interval(1000)
.withLatestFrom(isPersonalized$)
.map(bothValues => {
const searchResult = bothValues[0];
const isPersonalized = bothValues[1];
...
});
I'm trying to update the Angular2 Forms Validation example to handle an Async Validation response. This way I can hit an HTTP endpoint to validate a username.
Looking at their code they currently aren't currently using a Promise and it's working just fine:
/** A hero's name can't match the given regular expression */
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
const name = control.value;
const no = nameRe.test(name);
return no ? {'forbiddenName': {name}} : null;
};
}
I'm trying to update to return a Promise. Something like:
/** A hero's name can't match the given regular expression */
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl) => {
const name = control.value;
return new Promise( resolve => {
resolve({'forbiddenName': {name}});
});
};
}
However, the result I get doesn't display the error message, it's showing undefined.
My thought is it has something to do with the way they are handling displaying the errors:
onValueChanged(data?: any) {
if (!this.heroForm) { return; }
const form = this.heroForm;
for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
this.formErrors[field] += messages[key] + ' ';
}
}
}
}
However I'm not sure of a better way of doing this.
Angular2 example:
https://angular.io/docs/ts/latest/cookbook/form-validation.html#!#live-example
Link to my example attempting to return Promise:
https://plnkr.co/edit/sDs9pNQ1Bs2knp6tasgI?p=preview
The problem is that you add the AsyncValidator to the SyncValidator Array. AsyncValidators are added in a separate array after the SyncValidators:
this.heroForm = this.fb.group({
'name': [this.hero.name, [
Validators.required,
Validators.minLength(4),
Validators.maxLength(24)
],
[forbiddenNameValidator(/bob/i)] // << separate array
],
'alterEgo': [this.hero.alterEgo],
'power': [this.hero.power, Validators.required]
});