Link: https://angular.io/docs/js/latest/api/core/OnInit-interface.html, https://www.youtube.com/watch?v=bY92HFyaBvo

export interface OnInit

exported from angular2/core defined in angular2/src/core/linker/interfaces.ts (line 79)

Implement this interface to execute custom initialization logic after your directive's data-bound properties have been initialized.

ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

Keep it as a best pratices that implements OnInit, OnDestroy. Then inside ngOnInit, we call service to fetch data back. And in ngOnDestroy, we unsubscribe the Observable.

import {Component, ElementRef, EventEmitter, Output, OnInit, OnDestroy} from 'angular2/core';
import {Observable} from 'rxjs/Rx';
import {SearchServcie} from './SearchServcie'; @Component({
selector: 'search-input',
template: `<input type="text" autofocus>`
}) export class SearchInput implements OnInit, OnDestroy{ @Output() loading = new EventEmitter();
@Output() results = new EventEmitter(); private _subscription; constructor(
public youtube: SearchServcie,
private el:ElementRef) {} ngOnDestroy() {
// Unsubscribe the Observabler
console.log('ngOnDestroy');
     if(this._subscription) 
this._subscription.unsubscribe();
} ngOnInit() {
// Fetch the data from server
console.log("init");
const keyup$ = Observable.fromEvent(this.el.nativeElement, 'keyup');
const searchInput$ = keyup$
.debounceTime()
.map((e:any) => {
return e.target.value.trim();
})
.distinctUntilChanged()
.filter((val:string) => {
return val.length > ;
})
.do(() => {
this.loading.emit(true);
});
const query$ = searchInput$
.switchMap( (query) => this.youtube.doSearch(query)); this._subscription = query$.subscribe((videos) => {
this.results.emit(videos);
this.loading.emit(false);
}, (err) => {
console.log(err);
this.loading.emit(false);
}, () => {
this.loading.emit(false);
});
}
}

[Angular 2] implements OnInit, OnDestory for fetching data from server的更多相关文章

  1. Fetching data with Ajax小例子

    ajax获取数据示例: 示例1 通过ajax获取txt文件里面的内容示例: <html> <head> <title>Ajax at work</title& ...

  2. zookeeper提示Unable to read additional data from server sessionid 0x

    配置zookeeper集群,一开始配置了两台机器server.1和server.2. 配置参数,在zoo.cfg中指定了整个zookeeper集群的server编号.地址和端口: server.1=1 ...

  3. [Redux] Fetching Data on Route Change

    We will learn how to fire up an async request when the route changes. A mock server data: /** /api/i ...

  4. 『奇葩问题集锦』Ruby 切换淘宝源报错WARNING: Error fetching data: SSL_connect returned=1 errno=0 state=SSLv3 read s erver certificate B: certificate verify failed

    ===>首先需要使用https<===https://ruby.taobao.org/ 第一步 下载http://pan.baidu.com/s/1kU0rxtH 复制到ruby安装的根目 ...

  5. [Angular 2] Refactoring mutations to enforce immutable data in Angular 2

    When a Todo property updates, you still must create a new Array of Todos and assign a new reference. ...

  6. Kafka消费者拉取数据异常Unexpected error code 2 while fetching data

    Kafka消费程序间歇性报同一个错: 上网没查到相关资料,只好自己分析.通过进一步分析日志发现,只有在拉取某一个特定的topic的数据时报错,如果拉取其他topic的数据则不会报错.而从这个异常信息来 ...

  7. [Falcor] Return the data from server

    <!-- index.html --> <html> <head> <!-- Do _not_ rely on this URL in production. ...

  8. ngx通讯之可观察对象实现

    1.公共服务 //test.service.ts import {Injectable} from '@angular/core'; import {Subject} from 'rxjs/Subje ...

  9. angular6 页面加载数据时的loading提示

    使用npm安装ngx-loading模块 npm install --save ngx-loading 在app.module.ts中导入模块 import { BrowserModule } fro ...

随机推荐

  1. oracle的一知半解

    这里只讲第一次开发运用oracle数据库的.net程序遇到问题: 1.程序与oracle数据库在同一台的服务器,貌似设置好连接字符串就可以直接访问( 需要主要的问题: 字符串格式:Data Sourc ...

  2. (四 )Knockout - ViewModel 的使用3 - 对象属性变化的实时更新

    ko.observableArray()就可以自动检测属性,其实他只是监控对象,而不是对象中的属性 使用ko.observable()进行处理 DEMO1 实时更新属性 //定义user数据对象 va ...

  3. JS实现定时器(类似工行网银支付限时操作)

      js脚本内容: //5秒倒计时 var num = 0 ; var max = 5 ; var id = null ; id = setInterval(box , 1000) ; //1秒钟调用 ...

  4. 【Linux】 任务调度/计划 cron

    实时查看日志: tail -f /var/log/cron 显示任务调度 bash#crontab -u username -l 编辑 bash#crontab -u username -e 内容: ...

  5. xml代码

    修改和删除: <?php$doc=new DOMDocument();$doc->load("php.xml");$root=$doc->documentElem ...

  6. 猜数字-js

    var n = Math.round(Math.random()*10); //随机数 // alert(n); while(true){ var Onum = prompt('请输入1-10之间的数 ...

  7. log4net 学习笔记

    记入最基本的用法 : refer : http://www.cnblogs.com/aehyok/archive/2013/05/07/3066010.html <configuration&g ...

  8. Python socket 客户端和服务器端

    connection, address = socket.accept() 调 用accept方法时,socket会时入“waiting”状态.客户请求连接时,方法建立连接并返回服务器.accept方 ...

  9. COJ 0026 汉诺塔问题

    汉诺塔问题 难度级别:B: 运行时间限制:1000ms: 运行空间限制:51200KB: 代码长度限制:2000000B 试题描述 经典的汉诺塔游戏相信很多同学都会玩的,规则就不用赘述,百科一下就OK ...

  10. 【转】在Ubuntu 12.04 上为Virtualbox 启用USB 设备支持--不错

    原文网址:http://www.cnblogs.com/ericsun/archive/2013/06/10/3130679.html 虚拟机我一直在用,不是说离不开Windows,而是有些时候一些应 ...