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. Android开发手记(7) 按钮类控件的使用

    1.点击Button改变页面背景色 通过Button改变页面背景色,首先新建相应的对象,让后绑定到Layout上的元素. final RelativeLayout layout = (Relative ...

  2. Sql 中常用日期转换Convert(Datetime)

    CONVERT(data_type,expression[,style]) convert(varchar(10),字段名,转换格式) 说明:此样式一般在时间类型(datetime,smalldate ...

  3. 总结:如何获取同一个DIV里的多个不同子标签的值,并赋值给input?

    这个问题说起来简单,但对于新手来说,也着实卡了好久,并且我在网上搜了好久没能找到合适的答案, 于是去博问问了一下,得到许多大神们的帮助与回答,接下来我就总结一下能够实现这个效果的几种方法,既为了自己更 ...

  4. jvm参数设置

    -Xss: 栈大小 -Xms:堆初始化大小-Xmx:堆最大大小-XX:NewSize=n:设置伊甸区大小-XX:NewRatio=n:年轻代与年老代比值.如:为3,表示年轻代与年老代比值是1:3,   ...

  5. Java反射 - 3(动态代理)

    动态代理是对包装模式的升级,可以动态的传入需要代理的对象实现代理 准备如下 1. 被代理类的接口 2.被代理类 3.处理器:InvocationHandler 4.代理调用:Proxy.newInst ...

  6. swing菜单,常用组件,常用容器

    1菜单 import javax.swing.*; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event ...

  7. javascript DOM对象转jquery对象

    首先,假设一种情形:要在HTML文件中为一个select对象添加一个函数,这个函数的名字叫dynamic_change(this),当select的option被改变的时候调用onchange事件来处 ...

  8. validate插件深入篇

    1.使用valid()来验证表单是否填写正确: <form id="mainform"> <button id="check">< ...

  9. node学习笔记-搭建node环境

    最近项目要用到node,利用空闲整理做下笔记 第一步  安装node,方式比较多,最为直接的是直接去官网     可直接从官网下载安装http://nodejs.cn/download/ 根据自己情况 ...

  10. PHP生成数字+字符混合型字符串

    以下是一个用PHP随机生成字符+数字混合型的随机字符串,可用来生成会员ID.用户密码/密钥等内容,函数简单,代码如下: <?php function generate_rand($l){ $c= ...