[Angular 2] implements OnInit, OnDestory for fetching data from server
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的更多相关文章
- Fetching data with Ajax小例子
ajax获取数据示例: 示例1 通过ajax获取txt文件里面的内容示例: <html> <head> <title>Ajax at work</title& ...
- zookeeper提示Unable to read additional data from server sessionid 0x
配置zookeeper集群,一开始配置了两台机器server.1和server.2. 配置参数,在zoo.cfg中指定了整个zookeeper集群的server编号.地址和端口: server.1=1 ...
- [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 ...
- 『奇葩问题集锦』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安装的根目 ...
- [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. ...
- Kafka消费者拉取数据异常Unexpected error code 2 while fetching data
Kafka消费程序间歇性报同一个错: 上网没查到相关资料,只好自己分析.通过进一步分析日志发现,只有在拉取某一个特定的topic的数据时报错,如果拉取其他topic的数据则不会报错.而从这个异常信息来 ...
- [Falcor] Return the data from server
<!-- index.html --> <html> <head> <!-- Do _not_ rely on this URL in production. ...
- ngx通讯之可观察对象实现
1.公共服务 //test.service.ts import {Injectable} from '@angular/core'; import {Subject} from 'rxjs/Subje ...
- angular6 页面加载数据时的loading提示
使用npm安装ngx-loading模块 npm install --save ngx-loading 在app.module.ts中导入模块 import { BrowserModule } fro ...
随机推荐
- CUICatalog: Invalid asset name supplied: (null)
出现这个问题的根本原因是你调用了[UIImage imageNamed:name]这个方法 但是name = nil;所以报出该错误. 解决方法,在项目中搜索[UIImage imageNamed ...
- css布局之三栏布局
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name ...
- excel导出的集中情况
jsp 页面: 导出按钮: <form id="excel" name="exportForm" method="post" acti ...
- POJ 3254 状压DP
题目大意: 一个农民有一片n行m列 的农场 n和m 范围[1,12] 对于每一块土地 ,1代表可以种地,0代表不能种. 因为农夫要种草喂牛,牛吃草不能挨着,所以农夫种菜的每一块都不能有公共边. ...
- 《Linux内核分析》week1作业-分析一个简单c语言的汇编代码
1.C语言源码 #include <stdio.h> int g(int x){ ; } int f(int x){ return g(x); } int main(){ )+; } 2. ...
- 解决Windows服务1053错误方法
WCF使用MSMQ绑定寄宿在Windows服务上,但启动服务时出现1053错误 在网上搜索了N多解决方案,都是比较高深的扯到原理和系统bug等问题 看了看到最后也没有解决,最终我决定使用一个比较山寨的 ...
- 【学习笔记】【Foundation】数组
数组:可重复,有序 不可变数组 创建数组 //array开头的方法是类方法,init开头的是实例方法 //NSArray* arr=[[NSArray alloc]initWithObjects:@& ...
- T-SQL事务实例
begin try begin tran ,'); ; --RAISERROR ('Error raised in TRY block.',16,1); commit tran end try beg ...
- empty()方法
empty()可以用来检查一个变量是否被声明或者值为false,通常被用来检查一个表单变量是否被发送或者包含数据. 例如一个登录表单: <?php if(!empty($_POST['uname ...
- ural 1207 Median on the Plane
极角排序 #include <cstdio> #include <cstring> #include <algorithm> #include <cmath& ...