获取异步数据的方法有:
1.回调函数
2.promise
3.rxjs
1.回调函数
代码例子:
getCallBack(back){
setTimeout(() => {
var username:any="张三";
back(username);
}, 1000);
}
调用
2.promise
getPromiseData(){
return new Promise((resolve,reject)=>{
setTimeout(() => {
var userName = "李四";
resolve(userName);
}, 1000);
})
}
获取:
getPro(){
let str = this.method.getPromiseData();
str.then((data)=>{
console.log(data);
})
}
3.rxjs
导入:import { Observable} from 'rxjs';
getRxjs(){
//导入配置
return new Observable((observe)=>{
setTimeout(() => {
var str:any="王五";
observe.next(str);
//失败
//observe.error();
}, 1000);
})
}
subscribe()方法获得
getRxijData(){
var str = this.method.getRxjs();
var d= str.subscribe((value)=>{
console.log(value);
})
//撤销
// setTimeout(() => {
// d.unsubscribe();
// }, 4000);
}
*多次获取setInterval()
getNumbers(){
//导入配置
let count=0;
return new Observable((observe)=>{
setInterval(() => {
var str:any="赵六"+count;
observe.next(str);
//失败
//observe.error();
count++;
}, 1000);
})
}
map,filter
getFilterMap(){
let count:any=0;
return new Observable((observe)=>{
setInterval(()=>{
observe.next(count);
count++;
},1000);
})
}
getMapFilter(){
this.method.getFilterMap().pipe(
filter((value:any)=>{
if(value%2==0){
return value;
}
}),
map((value:any)=>{
return value*value;
})
).subscribe((data:any)=>{
console.log(data)
})
}