文章16 | 阅读 6587 | 点赞0
import { Component, OnInit } from '@angular/core';
import { CommonService } from '../../services/common.service';
import { Observable } from 'rxjs';
import { map, filter } from 'rxjs/operators';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.less']
})
export class HomeComponent implements OnInit {
constructor(public common: CommonService) {
} //注册服务
ngOnInit(): void {
//1. 异步回调
this.common.getDatacb((res) => {
console.log(res)
});
//2. promise获取
this.common.getPromise().then((res) => {
console.log(res);
})
//3. rxjs获取异步数据
var rxData = this.common.geRxjstData();
var p1 = rxData.subscribe(res => {
console.log(res);
})
//4. rxjs获取异步数据执行多次
this.common.getRxIntervalData().subscribe(res => {
console.log(res);
})
// 5. 过一秒以后撤回刚才的动作
setTimeout(() => {
p1.unsubscribe();
}, 1000)
//6. pipe
var stream = this.common.streamFun();
stream.pipe(
filter(val => val % 2 == 0), //过滤
map(value => {
return value * value; // 处理数据
})
)
.subscribe(res => {
console.log(res);
})
}
}
import { Injectable } from '@angular/core';
import { Observable } from "rxjs";//js库
@Injectable({
providedIn: 'root'
})
export class CommonService {
constructor() { }
///回调函数
getDatacb(cb) {
setTimeout(() => {
cb('getCBdata')
}, 1000)
}
//promise获取
getPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('张三----promise');
// resolve('张三----promise1');
// resolve('张三----promise2');
}, 1000)
})
}
//3. rxjs获取异步数据
geRxjstData() {
return new Observable(observer => {
setTimeout(() => {
var username = '小明 -- rxjs'
observer.next(username);
}, 3000)
})
}
//4. rxjs多次执行
getRxIntervalData() {
return new Observable(observer => {
var count = 0;
setInterval(() => {
count++;
var username = '小明 --rxjs-Interval'
observer.next(username + count);
}, 1000)
})
}
// promise : 不具备撤回 , 以及 多次执行, 但是Rxjs具备
streamFun() {
return new Observable<any>(observer => {
let count = 0;
setInterval(() => {
observer.next(count++);
}, 1000);
});
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://codeboy.blog.csdn.net/article/details/107828364
内容来源于网络,如有侵权,请联系作者删除!