He buscado durante bastante tiempo para entender cómo suscribirme a una matriz cuyos valores se actualizan constantemente.
Necesito entender cómo configurar mi servicio Angular 2+ observable correctamente y suscribirme correctamente en mi componente. Suponga que todas las demás partes del código funcionan correctamente.
@Injectable() export class AutocompleteService { searchTerm: string; results = []; observe$ = Observable.from(this.results); searchTest(term){ this.searchTerm = term.toLowerCase(); if(this.searchTerm.length > 2){ this.recruiters.forEach(function(el){ if(el.name.toLowerCase().indexOf(term) != -1) { this.results.push(el); } }); } } getCurrentResults():Observable<Object> { return this.observe$; } Todo en el servicio funciona como se esperaba. Si registro el term , obtengo la entrada del usuario de mi componente. O la matriz de results después de que se inserten los resultados de búsqueda coincidentes.
@Component({ selector: 'autocomplete', templateUrl: './autocomplete.component.html', providers: [AutocompleteService] }) export class AutocompleteComponent implements OnInit{ constructor(private autocompleteService: AutocompleteService){} value: string = ''; searchControl = new FormControl(); // fired when input happens getResults(event){ this.autocompleteService.searchTest(event.target.value); this.autocompleteService.getCurrentResults().subscribe( value => console.log(value) ); }Configuré el patrón observable lo mejor que pude, pero no obtengo nada de .subscribe en getResults
Además de lo que dijeron jonrsharpe y echonax :
puedes usar Asunto:
@Injectable() export class AutocompleteService { searchTerm: string; results = []; subject = new Subject(); searchTest(term){ this.searchTerm = term.toLowerCase(); if(this.searchTerm.length > 2){ this.recruiters.forEach(el =>{ if(el.name.toLowerCase().indexOf(term) != -1) { this.subject.next(el); } }); } } getCurrentResults():Subject<Object> { return this.subject; }}
y suscríbase a getCurrentResults() de la misma manera que lo hizo.
tu demostración: plunker
Hay muchos errores en tu código.
No hay un campo this.recruiters en su servicio
this.results.push(el); no empujará nada a los resultados porque está usando forEach(function(el){ debería haber sido forEach((el)=> para que this dentro del alcance se refiera a su servicio.
Plunker de ejemplo: http://plnkr.co/edit/5L0dE7ZNgpJSK4AbK0oM?p=preview