Angular2 @ TypeScript可观察到的错误

赫尔曼·弗兰森

我有一个输入字段,当用户键入搜索字符串时,我想等待用户在执行_heroService http请求之前停止键入至少300毫秒(反跳)。只有更改的搜索值才能将其传递到服务(distinctUntilChanged)。switchMap返回一个新的可观察值,该值合并了这些_heroService可观察值,并按其原始请求顺序对其进行了重新排列,并且仅将最新的搜索结果交付给订阅者。

我正在使用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);

英雄

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);
贡特·佐赫鲍尔(GünterZöchbauer)

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在angular2中手动引发可观察到的错误?

Angular 2可观察到多个订户

angular2等到条件可观察到完成

q.all对于angular2可观察到的

Angular 4-可观察到的捕获错误

具有bootstrap事件的Angular2不会触发可观察到的更改

在Angular2中,如何拦截可观察到的错误响应并将其传递给错误通道

在Angular2中可观察到的组件属性变化

Angular 2单元测试可观察到的错误(HTTP)

Angular2可观察到的共享不起作用

Angular 2缓存可观察到的http结果数据

可观察到的服务在组件NgOnInIt中不起作用-Angular2

Angular2可观察到的问题,无法读取未定义的属性“订阅”

返回可观察到的内部可观察到的可激活Angular 4防护

Angular HTTP可观察到的元组

Angular http请求可观察到的错误不捕获错误?

swagger codegen-> angular6:rxjs可观察到的编译错误

Angular RxJS可观察到的加载错误

rxjs + angular:错误“杀死”可观察到的Web服务调用错误

Angular 7如何在可观察到的地方获取HTTP错误的正文(json)

尝试向API发出多个请求时出现TypeScript可观察到的错误(Angular,TypeScript,RxJS)

Angular2 TypeScript可观察到的问题

ionic2-设备运动返回可观察到,但退订给出错误

Angular2可观察到的变化检测模板更新

angular2 rxjs可观察到的forkjoin

Angular2 http调用和典型的可观察到的问题

角度2可观察到可观察[]

如何取消订阅或处理Angular2或RxJS中可观察到的间隔?

Angular2可观察到的回调