request.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class RequestService {

constructor() { }
//1.同步
getData(){
return 'this is service data';
}

getCallbackData(cb:any){
setTimeout(() => {
var name = '张三';
// return name;
cb(name);
},1000);
}

getRxjsData(){

return new Observable((observable) => {
setTimeout(() => {
var name = '张三---rxjs';
//传入数据
observable.next(name);
// observable.error('错误数据');
},3000);
})
}

//多次执行

getRxjsIntervalData(){
let count = 0;
return new Observable((observable) => {
setInterval(() => {
count++;
var name = '张三---Interval'+count;
//传入数据
observable.next(name);
// observable.error('错误数据');
},3000);
})
}

getRxjsIntervalNum(){
let count = 0;
return new Observable((observable) => {
setInterval(() => {
count++;
observable.next(count);
// observable.error('错误数据');
},2000);
})
}

}

home.component.ts

import { Component, OnInit } from '@angular/core';
import { RequestService } from '../services/request.service';

import { map,filter } from 'rxjs/operators';


@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

constructor(public request:RequestService) { }

ngOnInit(): void {
//同步方法
let data = this.request.getData();
console.log(data);

//callback获取异步数据
this.request.getCallbackData((data:any)=>{
console.log(data);
});

//rxjs获取异步方法里面的数据
var rxjsData = this.request.getRxjsData();
rxjsData.subscribe((data) => {
console.log(data);
})

//过一秒以后撤回刚才的操作

var stream = this.request.getRxjsData();
var d = stream.subscribe((data) => {
console.log(data);
})

setTimeout(() => {
d.unsubscribe();//取消订阅
})

//rxjs执行多次
var streamInterval = this.request.getRxjsIntervalData();
//定时器
streamInterval.subscribe((data) => {
console.log(data);
})

//用工具方法对返回数据进行处理
var streamNum = this.request.getRxjsIntervalNum();
streamNum.pipe(
filter((value:any) => {
if(value%2==0){
return value;
}
}),
map((value) => {
return value * value;
})
)
.subscribe((data) => {
console.log(data);
})
}

}


Angular Rxjs异步编程_错误数据