retornar valor booleano de un observable

Como hago para que esta funcion retorne un valor verdadero o falso

autenticacion(){     let bool;     this.auth.autenticacion(this.auth.getToken()).subscribe(data=>{       if(data.data.token==this.auth.getToken()){         bool=true;       }else{         bool=false;       }     });     console.log(bool); return bool;   }  this.autenticacion(); 

cuando llamo la funcion compruebo que me devuelve con el console log pero me devuelve un valor undefined alguien sabe como hacer que me retorne el false o el true

why am i getting observable results instead of json data?

I am trying to get search results with ionic. my search.service.ts file produces the correct results {Raw: Array(4)} in console.log, but in post.page.ts the console.log produces results: Observable {} instead of {results: Array(4)}… and on post.page.html {{ post.title }} returns nothing at all. what could be the issue?

ionic v4 angular 7 windows 10

search.service.ts

import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators';  @Injectable({   providedIn: 'root' })  export class SearchService {    posturl = '...';    constructor(private http: HttpClient) { }    searchPostData(qword: string): Observable<any> {     return this.http.get(`$  {this.posturl}/$  {encodeURI(qword)}`).pipe(       map(results => {         console.log('Raw: ', results);         return results['posts'];       })     );   }    getPostDetails(postId: string) {     return this.http.get(`$  {this.postDetail}/$  {postId}`);   }  } 

blog.page.ts

import { Component, OnInit } from '@angular/core'; import { SearchService } from '../search.service'; import { Observable } from 'rxjs';  @Component({   selector: 'app-blog',   templateUrl: './blog.page.html',   styleUrls: ['./blog.page.scss'], }) export class BlogPage implements OnInit {    results: Observable<any>;   searchTerm = '';    constructor(private searchService: SearchService) { }    ngOnInit() {   }    searchChanged() {     this.results = this.searchService.searchPostData(this.searchTerm);     console.log('result: ', this.results);   }  } 

blog.page.html

<ion-list>   <ion-item button *ngFor="let post of (results | async)">     {{ post.title }}   </ion-item> </ion-list> 

Different results from the same observable when using subscribe vs. async pipe

I’m a hobbist and am learning angular by myself for an year. When trying to develop a custom pagination service to retrieve data from firebase I came up with an observable returning different arrays when using async pipe or normal subscription.

Basically, my observable uses scan operator to accumulate data fetched from firebase. It has 2 methods: init to fetch first data and set observable with initial data, and addData, that fetches more data.

After started the service and add some data, if I init it again, it will not reset the data if using normal subscription. But if using async pipe, the service resets data as expected. Why are subscription and async pipe having different behavior when are expected to have the same?

I created a simplified reproduction of the error in stackblitz:

When click “reset data” button, the return from subscription dont reset. And the same data returned by async pipe resets accordingly.

For now, I’m already using async pipe for my project, but still can’t understand why they both aren’t working the same way. Hope someone can help me to figure out.

Implementing custom observable classes

I want to implement my own custom observable class so I can have a hierarchy of components and the closest defined configuration item bubbles to the front.

<form controlClasses="formDefinedClass">   <group controlClasses="groupDefinedClass">     <control controlClasses="controlDefinedClass"></control>   </group> </form> 

The setter property of these inputs then passes the value to the next method of an observable.

@Input() set controlClasses(value: string) {   this.controlClasses$  .next(value); } 

My goal is to have the closest config push to the front. In the above example on the control the controlClasses observable will emit ‘controlDefinedClass’ but if I was to remove the property it would emit ‘groupDefinedClass’ as it is the closest config in the control hierarchy.

I have spent a bit of time looking through the source code of the rxjs repository and was looking for some advise on implementing my own observable classes. To solve the above requirement I have come up with two data structures.

One is the StackSubject. Demo at https://stackblitz.com/edit/angular-tdajza?file=src%2Fapp%2Fstack-subject.ts

The other is the PushStack. Demo at https://stackblitz.com/edit/angular-cnrttk?file=src%2Fapp%2Fpush-stack.ts

Should I be implementing the _subscribe method? The rxjs classes for subjects and behavour subjects do so but also have the comment /** @deprecated This is an internal implementation detail, do not use. */ Is this implementation detail likely to change in a future version of rxjs?

Is having a subject that subscribes to another observable as in my StackSubject good practice?

Is creating a private observable and exposing the subscribe of the private observable to implement my observable as in my PushStack good practice?

The two methods both fulfil my requirements but I personally prefer the push stack method but the stack subject offers the additional benefit of having the getValue() method and value property so you can get the closest push value without needing to subscribe.

Are there any devs who have implemented custom observable classes or have worked on the rxjs repository who can provide an opinion on my implementation of these obsevables?

Aguardar Observable

Boa noite,

Estou fazendo uma busca no ngOnInit por dados mocados no JSON. Quando eu chamo o metodo que me retorna os dados em um Observable e o instancio em um objeto, o mesmo chega vazio.

Acredito que este erro ocorra pelo o fato de eu ter vários Observables sendo executados e quando chamo o metodo que tambem me retorna um Observable o objeto não consegue ser carregado pelo o fato não dar tempo de aguardar os Observables concluirem.

Nesse caso, gostaria de saber como eu faço para aguardar a chega de todos os observables em uma execução no ngOnInit.

Coloquei um async await porem não solucionou o meu problema.

Se puderem ajudar, agradeço.

subscribe observable is printing any data

  private CTomatic(orders: Array<Order>): void { const Ct = Number(window.localStorage.getItem('defaultCookingTime')); if (orders.length > 0) {   orders.forEach(order => {     if (       order.partner_order_state === ORDER_STATE.NEWORDER &&       (window.localStorage.getItem('cookingTime') === 'true' ? true : false)     ) {       this.ordersService       .takeOrder(order.id, this.cookingTime(order, Ct))       .retry(5)       .subscribe(         result => {           this.autoPrinter();           this.autoupdatethatshit();         },         (err: HttpErrorResponse) => {           const error = err.error ? err.error.error.message : err.statusText;           this.snackbarService.showMessageSnackbar(error);           this.autoupdatethatshit();         }       );     }   }); } 

}

my bug is that when i reach to this.autoPrinter(); they should print a text that is working fine, i think that the problem is on the observable but im stuck on that dont know if is something else i really need help on that !!!

public autoPrinter(): void { if (this.notificationPrintIsEnable === true) {   window.setTimeout(() => this.printerService.print(), 2000); } 

}

  public autoupdatethatshit(): void { setTimeout(() => {   this.ordersService.getOrders(); }, 5000); 

}

i cant understand the different between these 3 define observable ,

what’s the different ???!!! i’m confused , all of them is worked but i don’t know which of them is better

1- const myObservable2 = Observable.create(function (observer2:string)  {...} 2- const myObservable2 = Observable.create(function subscribe(observer2:string) {...} 3- const myObservable2 = Observable.create(function (observer2:Observer<string>) {...}  myObservable2.subscribe(function (data2: string) {           console.log(data2);             }) 

KO observable array

I am building a custom form on checkout and render data on real time from this form inputs

i get JSON data array value from ko in this way

information: function () {                 return this.source.get('information');             } 

and in my html template i call

<h3 data-bind="text: ' Città  : ' + information().shipping.citta"></h3> 

but how can i make this value observable?

Angular/RxJS – Nested Observable – Refactor Statement

I’m attempting to load departments from the server and populate a dropdown. If there’s a routeParam (dep) present, I’d like to set the formControl (department) to the targeted item.

The nested pipe statements seems a bit off to me, but I’m still relatively new to RxJS. Is there a better way to write the assignment statement for department$ ?

public form: FormGroup; public departments$  : Observable<Department[]>;  constructor(   private route: ActivatedRoute,   private departmentService: DepartmentService) {}  get department() {    return this.form.get('department') as FormControl; }  ngOnInit() {     this.form = new FormGroup({       department: new FormControl('', Validators.required)     });      this.departments$   = this.route.paramMap.pipe(       switchMap(         (params: ParamMap) => {           return this.departmentService.getDepartments().pipe(             tap(departments => {               if (params.has('dep') && departments && departments.length) {                 this.department.setValue(departments.find(dep => dep.id === +params.get('dep')));               }             })           );         }       )     ); } 

Angular 7. Al usar un Observable se refresca la página sin solicitarlo

Cuando hago una llamada http desde un componente todo funciona correctamente, pero si lo hago a través de un servicio creado por mí tras devolverme el resultado de la llamada la página se refresca automáticamente. Creo que este comportamiento puede tener algo que ver con el Observable, pero no sé cuál es el problema

Llamada que funciona correctamente: 
    deleteBrand(brand: Brand) {      if (confirm("¿Estás seguro que deseas eliminar el registro?")) {        return this.http.delete(`http://localhost:3000/api/brand/$  {brand._id}`)        .pipe(          tap(_ => this.deleteElementFromBrands(brand))        );      }     }      private deleteElementFromBrands(brand: Brand) {       console.log(JSON.stringify(brand));       var i = this.findIndex(this.brands, brand);       this.brands.splice(i, 1);     }            private findIndex(array: any[], item: any): number {       var i = 0;       for (i; i < array.length; i++) {         if (array[i]._id == item._id) {           return i;         }       }       return -1;     }

En cambio, si uso este otro código se produce el refresco automático de la página, lo cual no es deseable

Llamada que refresca la página de forma indeseada 
// --- listbrands.component.ts    deleteBrand(brand: Brand) {     if (confirm("¿Estás seguro que deseas eliminar el registro?")) {       this.brandService.deleteBrand(brand._id)       .subscribe(         res =>          this.deleteElementFromBrands(brand)       );     }   }   //---- Y el servicio //---- brandService.component.ts   deleteBrand (id: string): Observable<any> {   return this.http.delete(`$  {this.domain}$  {this.brandUrl}/$  {id}`)   .pipe(     tap(_ => console.log(`deleted item id=$  {id}`))   ); }