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 {
this.common.getDatacb((res) => {
console.log(res)
});
this.common.getPromise().then((res) => {
console.log(res);
})
var rxData = this.common.geRxjstData();
var p1 = rxData.subscribe(res => {
console.log(res);
})
this.common.getRxIntervalData().subscribe(res => {
console.log(res);
})
setTimeout(() => {
p1.unsubscribe();
}, 1000)
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";
@Injectable({
providedIn: 'root'
})
export class CommonService {
constructor() { }
getDatacb(cb) {
setTimeout(() => {
cb('getCBdata')
}, 1000)
}
getPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('张三----promise');
}, 1000)
})
}
geRxjstData() {
return new Observable(observer => {
setTimeout(() => {
var username = '小明 -- rxjs'
observer.next(username);
}, 3000)
})
}
getRxIntervalData() {
return new Observable(observer => {
var count = 0;
setInterval(() => {
count++;
var username = '小明 --rxjs-Interval'
observer.next(username + count);
}, 1000)
})
}
streamFun() {
return new Observable<any>(observer => {
let count = 0;
setInterval(() => {
observer.next(count++);
}, 1000);
});
}
}