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. .NET中删除空白字符串的10大方法

    介绍 我们有无数方法可用于删除字符串中的所有空白.大部分都能够在绝大多数的用例中很好工作,但在某些对时间敏感的应用程序中,是否采用最快的方法可能就会造成天壤之别. 如果你问空白是什么,那说起来还真是有 ...

  2. Swift和OC混编时, 关于@objc的作用

    Objective-C 和 Swift 在底层使用的是两套完全不同的机制,Cocoa 中的 Objective-C 对象是基于运行时的,它从骨子里遵循了 KVC (Key-Value Coding,通 ...

  3. PHP E-mail

    PHP E-mail 注入 首先,请看上一章中的 PHP 代码: <html><body> <?phpif (isset($_REQUEST['email']))//if ...

  4. Revenge of Fibonacc

    算法:搜索: In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence rela ...

  5. HTTP状态码:400\500 错误代码

    一些常见的状态码为: 200 - 服务器成功返回网页404 - 请求的网页不存在503 - 服务不可用详细分解: 1xx(临时响应)表示临时响应并需要请求者继续执行操作的状态代码. 代码  说明100 ...

  6. arclist标签和list标签区别

    很多站长朋友在刚入门织梦的时候对织梦的标签存在很多的困惑,关于arclist标签和list标签,甚至不知道啥时候用arclist,啥时用list标签.arclist 为自由列表,全局模板中都生效,一般 ...

  7. 如何使用service命令来管理nginx

    如何使用service命令来管理nginx??? 如: service nginx start service nginx restart service nginx stop service ngi ...

  8. Install and use Karma

    1:安装karma y@y:~$ npm install --global karma 2:安装karma插件 y@y:~$ npm install --global karma-jasmine ka ...

  9. java中gson的简单使用

    把从数据库中查询的记录以JSON格式返回给客户端,在这里使用gson-2.2.4.jar包. 代码结构如下: 数据库结构如下: (1)User.java public class User { pri ...

  10. 来一个可能防止恶意采集和爬虫的SH

    没办法,公司的要求,还有,一些山寨爬虫完全不够我们运维人员的感觉, 一天爬虫搞个三四十万的LOG,那我只好干了.. 人家GOOGLE,BAIDU,一天大约也就五六千吧.. 有一个小的SSH技巧,是判断 ...