错误TS2322:类型'()=> Observable <>'无法分配给类型'Observable <>'

时间:2018-09-01 04:36:30

标签: angular caching rxjs

我试图在我使用rxjs构建的Angular CLI应用程序中缓存一些静态数据。

我已遵循本教程:https://blog.thoughtram.io/angular/2018/03/05/advanced-caching-with-rxjs.html

我的设置:

  • Angular Cli版本:6.0.8
  • Angular Core版本:5.2.11
  • rxjs版本:5.5.11

但是我在ng服务中遇到了这个奇怪的错误:

  

错误TS2322:类型“()=>可观察”不能分配给类型“可观察”。属性“ _isScalar”丢失   类型为(()=>可观察”。

以及我的Google chrome控制台中的以下错误:

*strategy.html:60 ERROR Error: InvalidPipeArgument: 'function () {
        if (!this.cacheStrategies) {
            console.log("Strategies Cache Empty - reloading");
            this.cacheStrategies = this.getStrategies().pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__["shareReplay"])(CACHE_SIZE));
        }
        return this.cacheStrategies;
    }' for pipe 'AsyncPipe'
    at invalidPipeArgumentError (common.js:4283)
    at AsyncPipe.push../node_modules/@angular/common/esm5/common.js.AsyncPipe._selectStrategy (common.js:5732)
    at AsyncPipe.push../node_modules/@angular/common/esm5/common.js.AsyncPipe._subscribe (common.js:5714)
    at AsyncPipe.push../node_modules/@angular/common/esm5/common.js.AsyncPipe.transform (common.js:5688)
    at Object.eval [as updateDirectives] (GuidedTradeComponent.html:61)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:14697)
    at checkAndUpdateView (core.js:13844)
    at callViewAction (core.js:14195)
    at execEmbeddedViewsAction (core.js:14153)
    at checkAndUpdateView (core.js:13845)*

这就是我在 dataservice.ts

中所拥有的
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { map, shareReplay } from 'rxjs/operators';

const CACHE_SIZE = 1;

@Injectable()
export class DataService {

  constructor(private http:HttpClient) {}

  private cacheStrategies: Observable<Array<StrategyI>>;

  private getStrategies() {
      return this.http.get<StrategyResponse>('api.optionstrac.com/strategy').pipe(
        map(response => response.value)
      );
  }

  getStrategiesO() {
    if (!this.cacheStrategies) {
      console.log("Strategies Cache Empty - reloading");
      this.cacheStrategies = this.getStrategies().pipe(
        shareReplay(CACHE_SIZE)
      );
    }
    return this.cacheStrategies;
  }

}

export interface StrategyI {
  stratId: number;
  stratName: string;
  stratDesc: string;
  stratBe? : string;           
  stratAlsoKnownAs? : string;  
  stratMoreInfoUrl? : string;
}

export interface StrategyResponse {
  type: string;
  value: Array<StrategyI>;
} 

这就是我在 strategy.component.ts

中所拥有的
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { DataService, StrategyI } from '../../services/data.service';

@Component({
  selector: 'strategy',
  templateUrl: './strategy.html',
  styleUrls: ['./strategy.css']
})

export class StrategyComponent implements  OnInit {

  strategies: Observable<Array<StrategyI>>;

    constructor( private dataService: DataService )

  ngOnInit() {
    this.strategies = this.dataService.getStrategiesO;     <--- line with ERROR
  }
}

最后,这就是我对 strategy.component.html

的要求
  <select id="Strategy" formControlName="Strategy" >  
    <option value="0">--Select--</option>  
    <option *ngFor="let strategy of strategies | async" value={{strategy.stratId}}>{{strategy.stratName}}</option>  
  </select> 

我也尝试过更改行:

import { Observable } from 'rxjs/Observable';

只是:

import { Observable } from 'rxjs';

但是我没有想让它正常工作。...

3 个答案:

答案 0 :(得分:0)

getStrategiesO是一个函数,请调用它,现在您只需尝试在strategies

中复制此函
  ngOnInit() {
    this.strategies = this.dataService.getStrategiesO();
  }

答案 1 :(得分:0)

好像那里有错字

ngOnInit() { this.strategies = this.dataService.getStrategiesO; <--- line with ERROR }

如果应该是

ngOnInit() { this.strategies = this.dataService.getStrategiesO(); <--- the brackets }

我衷心希望这不是原因

答案 2 :(得分:0)

我可以使用它,以便使用Observable和rxjs在Angular中缓存数据

Dataservice.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { map, shareReplay } from 'rxjs/operators';

const CACHE_SIZE = 1;

@Injectable()
export class DataService {

  constructor(private http:HttpClient) {}

  private cacheStrategies: Observable<StrategyI[]>;     <---- changed this line

  private getStrategies() {
      return this.http.get<StrategyI[]>('http://api.optionstrac.com/strategy');
      //cast straight to Strategy interface array and removed the pipe and the map
  }

  get getStrategiesO() {             <---- was missing the get
    if (!this.cacheStrategies) {
      console.log("Strategies Cache Empty - reloading");
      this.cacheStrategies = this.getStrategies().pipe(
        shareReplay(CACHE_SIZE)
      );
    }
    else {
      console.log("Strategies loaded from Cache");
    }   
    return this.cacheStrategies;
  }

}

export interface StrategyI {
  stratId: number;
  stratName: string;
  stratDesc: string;
  stratBe? : string;           
  stratAlsoKnownAs? : string;  
  stratMoreInfoUrl? : string;
}
// no longer needed strategyresponse interface

strategy.component.ts

//strategies: Observable<Array<StrategyI>>;
strategies: Observable<StrategyI[]>;      <--- had to keep as Observable, but got rid of array

ngOnInit() {
  this.strategies = this.dataService.getStrategiesO;
}