NgZone在服务中未定义

时间:2018-06-26 08:05:50

标签: angular

我有这样的服务

import {Injectable, NgZone} from "@angular/core";
import {Mediafilepicker} from "nativescript-mediafilepicker";
import {Observable} from "rxjs/Observable";
import {NO_IMAGE_SELECTED} from "~/mediapicker.service";

@Injectable()
export class MediaPicker {
    constructor(private zone: NgZone) {}

    pick(types, page) {
        return Observable.create(observer => {
            const picker = new Mediafilepicker();

            picker.on('getFiles', (res: any) => {
                this.zone.run(() => {
                    if (!res.files.length) {
                        observer.error(NO_IMAGE_SELECTED);
                        return;
                    }

                    observer.next(res.files.split(',')[0]);
                    observer.complete();
                })
            });

            picker.on("error", res => {
                this.zone.run(() => {
                    observer.error(res);
                    observer.complete();
                });
            });

            picker.startFilePicker({
                android: {
                    enableImagePicker: !types || types.length == 2 || (types.length == 1 && types[0] == 'image'),
                    enableVideoPicker: !types || types.length == 2 || (types.length == 1 && types[0] == 'video'),
                    enableCameraSupport: true,
                    mxcount: 1,
                }
            });
        });
    }
}

调用“ getFiles”上的回调时会崩溃,错误为“无法读取未定义的属性” run”。

该服务中未定义区域怎么可能?

编辑:这似乎只是AOT的问题。 JIT一切正常

2 个答案:

答案 0 :(得分:0)

我会尝试的(但是我不知道是否可以工作:()

return Observable.create(observer => {
        const picker = new Mediafilepicker();
        //Use an auxiliar variable
        let zone=this.zone; //here I'm sure this.zone is really this.zone
        picker.on('getFiles', (res: any) => {
            zone.run(() => {  //<--use zone, not this.zone
                ...
            })
        })
        ...
        })

答案 1 :(得分:0)

尽管我的“信号处理”看起来很正确,但我仍然为我的SignalR驱动的数据更新而苦苦挣扎,这些数据更新没有传播到浏览器。

似乎@Carsten建议您不能在单例服务中使用NgZone。解决方案就是将NgZone注入使用Observable的组件中(在OP的情况下为“ observer.next(res.files.split(',')[0]);“)。

此处示例...

服务: (提取)

messageSubscription: Subscription;

constructor(private _service: NotificationService, private _ngZone: NgZone) {
    this.messageSubscription = this._service.message$
      .subscribe((message) => {

        // NgZone works perfectly here in the component, 
        // and the display component updates automatically as expected
        _ngZone.run(() => this.handleDataUpdate(message));
      });
  }

组件: (提取)


$request = new PaymentCreateRequest();
$request->body = $body;

$client = $this->getPayPalClient();//Preformed client
$result = $client->execute($request);

//And use $result->result->links[1]->href ...