Angular2 @ TypeScript Observable 错误

Posted

技术标签:

【中文标题】Angular2 @ TypeScript Observable 错误【英文标题】:Angular2 @ TypeScript Observable error 【发布时间】:2016-06-05 12:43:18 【问题描述】:

我有一个输入字段,当用户输入搜索字符串时,我想等待用户停止输入至少 300 毫秒(去抖动),然后再执行 _heroService http 请求。只有更改的搜索值才能通过服务 (distinctUntilChanged)。 switchMap 返回一个新的 observable,它结合了这些 _heroService observables,按照原始请求顺序重新排列它们,并且只向订阅者提供最近的搜索结果。

我正在使用 Angular 2.0.0-beta.0 和 TypeScript 1.7.5。

我怎样才能让这个东西正常工作?

我得到编译错误:

Error:(33, 20) TS2345: Argument of type '(value: string) => Subscription<Hero[]>' is not assignable to parameter of type '(x: , ix: number) => Observable<any>'.Type 'Subscription<Hero[]>' is not assignable to type 'Observable<any>'. Property 'source' is missing in type 'Subscription<Hero[]>'.
Error:(36, 31) TS2322: Type 'Hero[]' is not assignable to type 'Observable<Hero[]>'. Property 'source' is missing in type 'Hero[]'.

运行时错误(在搜索输入字段中键入第一个键后):

EXCEPTION: TypeError: unknown type returned
STACKTRACE:
TypeError: unknown type returned
at Object.subscribeToResult (http://localhost:3000/rxjs/bundles/Rx.js:7082:25)
at SwitchMapSubscriber._next (http://localhost:3000/rxjs/bundles/Rx.js:5523:63)
at SwitchMapSubscriber.Subscriber.next (http://localhost:3000/rxjs/bundles/Rx.js:9500:14)
...
-----async gap----- Error at _getStacktraceWithUncaughtError 
EXCEPTION: Invalid argument '[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]' for pipe 'AsyncPipe' in [heroes | async in Test@4:16]

test1.ts

import bootstrap         from 'angular2/platform/browser';
import Component         from 'angular2/core';
import HTTP_PROVIDERS    from 'angular2/http';

import Observable        from 'rxjs/Observable';
import Subject           from 'rxjs/Subject';
import 'rxjs/Rx';

import Hero              from './hero';
import HeroService       from './hero.service';

@Component(
    selector: 'my-app',
    template: `
        <h3>Test</h3>
        Search <input #inputUser (keyup)="search(inputUser.value)"/><br>
        <ul>
            <li *ngFor="#hero of heroes | async">hero.name</li>
        </ul>
    `,
    providers: [HeroService, HTTP_PROVIDERS]
)

export class Test 

    public errorMessage: string;

    private _searchTermStream = new Subject<string>();

    private heroes: Observable<Hero[]> = this._searchTermStream
        .debounceTime(300)
        .distinctUntilChanged()
        .switchMap((value: string) =>
            this._heroService.searchHeroes(value)
                .subscribe(
                    heroes => this.heroes = heroes,
                    error =>  this.errorMessage = <any>error)
        )

    constructor (private _heroService: HeroService) 

    search(value: string) 
        this._searchTermStream.next(value);
    


bootstrap(Test);

英雄.ts

export interface Hero 
    _id: number,
    name: string

hero.service.ts

import Injectable     from 'angular2/core';
import Http, Response from 'angular2/http';
import Headers, RequestOptions from 'angular2/http';
import Observable     from 'rxjs/Observable';
import 'rxjs/Rx';

import Hero           from './hero';

@Injectable()

export class HeroService 

    private _heroesUrl = 'api/heroes';

    constructor (private http: Http) 

    getHeroes () 
        return this.http.get(this._heroesUrl)
            .map(res => <Hero[]> res.json())
            .do(data => console.log(data))
            .catch(this.handleError);
    

    searchHeroes (value) 
        return this.http.get(this._heroesUrl + '/search/' + value )
            .map(res => <Hero[]> res.json())
            .do(data => console.log(data))
            .catch(this.handleError);
    

    addHero (name: string) : Observable<Hero>  

        let body = JSON.stringify(name);
        let headers = new Headers( 'Content-Type': 'application/json' );
        let options = new RequestOptions( headers: headers );

        return this.http.post(this._heroesUrl, body, options)
            .map(res =>  <Hero> res.json())
            .do(data => console.log(data))
            .catch(this.handleError)
    

    private handleError (error: Response) 
        // in a real world app, we may send the server to some remote logging infrastructure
        // instead of just logging it to the console
        console.log(error);
        return Observable.throw('Internal server error');
    

index.html

<!DOCTYPE html>
<html>
  <head>
    <base href="/">
    <script src="angular2/bundles/angular2-polyfills.js"></script>
    <script src="typescript/lib/typescript.js"></script>
    <script src="systemjs/dist/system.js"></script>
    <script src="angular2/bundles/router.dev.js"></script>
    <script src="rxjs/bundles/Rx.js"></script>
    <script src="angular2/bundles/angular2.js"></script>
    <script src="angular2/bundles/http.dev.js"></script>
    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
    <script>
      System.config(
        transpiler: 'typescript',
        typescriptOptions:  emitDecoratorMetadata: true ,
        packages: 'components': defaultExtension: 'ts'
      );
      System.import('components/test1')
            .then(null, console.error.bind(console));
    </script>
  </head>
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

这是另一个版本“test2.ts”,可以在每个(keyup)事件后正常执行 http 请求:

import bootstrap         from 'angular2/platform/browser';
import Component         from 'angular2/core';
import HTTP_PROVIDERS    from 'angular2/http';

import Hero              from './hero';
import HeroService       from './hero.service';

@Component(
    selector: 'my-app',
    template: `
        <h3>Test</h3>
        Search <input #inputUser (keyup)="search(inputUser.value)"/><br>
        <ul>
            <li *ngFor="#hero of heroes">hero.name</li>
        </ul>
    `,
    providers: [HeroService, HTTP_PROVIDERS]
)

export class Test 

    public heroes:Hero[] = [];
    public errorMessage: string;

    constructor (private _heroService: HeroService) 

    search(value: string) 
        if (value) 
            this._heroService.searchHeroes(value)
                .subscribe(
                    heroes => this.heroes = heroes,
                    error =>  this.errorMessage = <any>error);
        
        else 
            this.heroes = [];
        
    


bootstrap(Test);

【问题讨论】:

您最好升级您的 Angular 2 参考,因为它不再处于测试阶段 【参考方案1】:

.subscribe(...) 返回 Subscription,而不是 Observable。 删除 subscribe(...) 或将其替换为 .map(...) 并在访问时使用 .subscribe(...) 来获取值。

【讨论】:

非常感谢您的帮助。你能再具体一点吗? Observables 对我来说非常困难。我应该把.subscribe(..) 块放在哪里? 你提供了很多代码,我没有完全调查。我发现 *ngFor="#hero of heroes" 应该与 *ngFor="#hero of heroes | async" 一起使用,并且 async 会为您执行 subscribe(),否则您想要访问值 this.heroes.subscribe(...) 感谢您的耐心等待,我是新手 ;-) 我将 this.heroes.subscribe(...) 放在哪里以及如何准确?我猜到了生命周期钩子ngOnChanges () this.heroes.subscribe(...) ,但这会产生运行时错误:EXCEPTION: Cannot find a differ supporting object '[object Object]' in [heroes in Test@4:16] 和编译错误:Error:(39, 23) TS2322: Type 'Hero[]' is not assignable to type 'Observable&lt;Hero[]&gt;'. Property 'source' is missing in type 'Hero[]'. 问题是你是否需要它。您是否尝试过仅删除 subscribe(...) 部分?您已经在使用 | async 管道,应该这样做。否则我想这需要一个正在运行的 plunker,否则仅查看静态代码就太复杂了。 是的,使用 | async 管道可以工作。谢谢...但我更喜欢使用.subscribe(...),因为我也可以在其中进行错误处理。我也喜欢学习它是如何工作的......

以上是关于Angular2 @ TypeScript Observable 错误的主要内容,如果未能解决你的问题,请参考以下文章

typescript 测试OBS-todos2.component.ts

typescript 测试OBS-todos1.component.ts

typescript 测试OBS-todos0.component.ts

typescript 测试OBS-todos.component.spec.ts

在 Angular2 中访问 Typescript 对象变量

在 Angular2 TypeScript 中注释(出)代码