Skip to content

Instantly share code, notes, and snippets.

@DevEarley
Last active October 3, 2018 17:02
Show Gist options
  • Save DevEarley/76208ac83e6c27bb5cb664f7979605cb to your computer and use it in GitHub Desktop.
Save DevEarley/76208ac83e6c27bb5cb664f7979605cb to your computer and use it in GitHub Desktop.
More Angular Tricks (Observables)

This doc is using Angular 6 with Angular CLI.

Using DEBOUNCE with ngModel

HTML

	<p>
		<input [(ngModel)]="txtQuery" (ngModelChange)="onFieldChange($event)"/>
		{{letterCount}}
	</p>

Component

	import { Component } from '@angular/core';
	import { Subject } from 'rxjs';

	import { debounceTime,distinctUntilChanged } from 'rxjs/operators';
	@Component({
		selector: 'app-ngmodel',
		templateUrl: './ngmodel.component.html',
		styleUrls: ['./ngmodel.component.css']
	})
	export class NgmodelComponent {
		letterCount: string;
		txtQuery: string; // bind this to input with ngModel
		txtQueryChanged: Subject<string> = new Subject<string>();
		constructor() {
			this.txtQueryChanged.pipe(debounceTime(1000),
			distinctUntilChanged()).subscribe(model => {
				this.txtQuery = model;
				this.letterCount = model.length.toString();
			});
		}
		onFieldChange(query:string){
		this.txtQueryChanged.next(query);
		}
	}

Using Subscribe to service

Service

	import { Injectable } from '@angular/core';
	import { URLSearchParams, Jsonp } from '@angular/http';
	import { Observable } from 'rxjs';
	import { map } from 'rxjs/operators';
	@Injectable({
	  providedIn: 'root'
	})
	export class WikiSearchService {

	  constructor(private jsonp: Jsonp) {}

	  search(term: string) {
	    var search = new URLSearchParams()
	    search.set('action', 'opensearch');
	    search.set('search', term);
	    search.set('format', 'json');
	    return this.jsonp
			.get('http://en.wikipedia.org/w/api.php?callback=JSONP_CALLBACK', { search })
			.pipe(map((request) => request.json()[1]));
	  }
	}

Usage

	import { WikiSearchService } from '../services/wiki-search.service';
	...
	@Component({
	  providers: [WikiSearchService],
	 ...
	this.wikiSearchService.search(this.txtQuery).subscribe(data => { 
          this.result = data;
        });

Using a Form Control

HTML

	<form [formGroup]="userForm"
		(ngSubmit)="onFormSubmit()">
		Name:
		<input formControlName="name"
			placeholder="Enter Name"> Age:
		<input formControlName="age"
			placeholder="Enter Age">
		<button type="submit">Submit</button>
	</form>
	{{usrNameChanges}}

Component

	import { FormControl, FormGroup } from '@angular/forms';
	...
	userForm = new FormGroup({
		name: new FormControl(),
		age: new FormControl('20')
	});
	usrNameChanges: string;
	constructor() {
		this.userForm.get('name').valueChanges.subscribe(data => this.usrNameChanges = data);
	}
	onFormSubmit(): void {
		console.log('Name:' + this.userForm.get('name').value);
	}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment