環(huán)境:Angular2+現(xiàn)在有一個(gè)組件內(nèi)部classDemo01{data$:Observable;constructor(privateservice:MyService){}OnInit(){this.data$=this.service.getData();}submit(){//在這里我需要拿到this.data$中的數(shù)據(jù)去做一些處理//如果直接對(duì)this.data$進(jìn)行訂閱的話(huà),就會(huì)進(jìn)入MyService中的getData()方法重新獲取一次數(shù)據(jù),但是我不想這樣//**目前我的辦法是,看下面的ts**}}Service:classMyService{getData():Observable{returnof(['1','2','3','4'])//這里有可能是個(gè)http請(qǐng)求}}模板:{{item}}Submit我的解決辦法是:classDemo01{data$:Observable;data:string[]constructor(privateservice:MyService){}OnInit(){this.data$=this.service.getData().pipe(//使用tap操作符監(jiān)控this.data$,將其中的數(shù)據(jù)緩存一份到this.datatap(data=>{this.data=data;}));}submit(){//在這里使用this.data}}不知道是否還有其他的操作能夠解決這種場(chǎng)景呢?
跪求!Observable使用場(chǎng)景的一個(gè)問(wèn)題
寶慕林4294392
2019-11-03 09:41:14