当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript Observable.create方法代码示例

本文整理汇总了TypeScript中rxjs.Observable.create方法的典型用法代码示例。如果您正苦于以下问题:TypeScript Observable.create方法的具体用法?TypeScript Observable.create怎么用?TypeScript Observable.create使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rxjs.Observable的用法示例。


在下文中一共展示了Observable.create方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: getAll

 /**
  * Busca en el cache local o el servidor los pediles 
  * 
  * @returns {Observable<Array<Perfil>>}
  * Exito: {Array<Perfil>}
  * Falla: {Response}
  */
 private getAll(): Observable<Array<Perfil>> {
   if (this.perfiles) {
     return Observable.create(obs => { obs.next(this.perfiles); });
   } else {
     return Observable.create(obs => {
       this.localGetAll().subscribe(doc => {
         this.perfiles = doc;
         obs.next(this.perfiles);
       }, erro => {
         this.serverGetAll().subscribe(res => {
           if (res.response) {
             this.perfiles = res.result;
             this.localSavePerfiles(this.perfiles).subscribe(doc => {
               obs.next(this.perfiles);
             }, err => {
               obs.next(this.perfiles);
             })
           } else {
             obs.error(res);
           }
         }, err => {
           let r = new ResponseClass.Response(false, ResponseClass.RES_SERVER_ERROR, 'Sin Conexiรณn!');
           obs.error(r);
         })
       })
     });
   }
 }
开发者ID:sclMAX,项目名称:INDUMATICS,代码行数:35,代码来源:perfiles.ts

示例2: getAll

 /**
  * Retorna los Colores 
  * 
  * @returns {Observable<Array<Color>> }
  * Exito: {Array<Color>}
  * Falla: {Rosponse}
  */
 public getAll(): Observable<Array<Color>> {
   if (this.colores) {
     return Observable.create(obs => {
       obs.next(this.colores);
       obs.complete();
     });
   } else {
     return Observable.create(obs => {
       this.localGetAll().subscribe(doc => {
         this.colores = doc;
         obs.next(this.colores);
         obs.complete();
       }, err => {
         this.serverGetAll().subscribe(res => {
           if (res.response) {
             this.colores = res.result;
             this.localSaveColores(this.colores).subscribe(doc => {
               obs.next(this.colores);
             })
             obs.next(this.colores);
             obs.complete();
           } else {
             obs.error(res);
           }
         }, err => {
           let r = new ResponseClass.Response(false, ResponseClass.RES_SERVER_ERROR, 'Sin Conexiรณn');
           obs.error(r);
         });
       })
     })
   }
 }
开发者ID:sclMAX,项目名称:INDUMATICS,代码行数:39,代码来源:colores.ts

示例3: create

  private create(url): WebSocketConnection {
    const ws = new WebSocket(url);

    const openObservable = Rx.Observable.create((obs: Rx.Observer<MessageEvent>) => {
      ws.onopen = obs.next.bind(obs);
      ws.onerror = obs.error.bind(obs);
      ws.onclose = obs.complete.bind(obs);
      return ws.close.bind(ws);
    });

    const messageObservable = Rx.Observable.create((obs: Rx.Observer<MessageEvent>) => {
      ws.onmessage = obs.next.bind(obs);
      ws.onerror = obs.error.bind(obs);
      ws.onclose = obs.complete.bind(obs);
      return ws.close.bind(ws);
    });

    const messageObserver = {
      next: (data: Object) => {
        if (ws.readyState === WebSocket.OPEN) {
          ws.send(JSON.stringify(data));
        }
      }
    };

    return {open: openObservable, messages: Rx.Subject.create(messageObserver, messageObservable)};
  }
开发者ID:Servoy,项目名称:servoy-eclipse,代码行数:27,代码来源:websocket.service.ts

示例4: uploadFiles

  uploadFiles(options, files, fileType) {

    if (!this.validateFile(files[0], fileType)) {
      return Observable.create(observer => {
        observer.next({});
        observer.complete();
      })
    }

    return Observable.create(observer => {
      const uploader = new Ng2Uploader();
      uploader.setOptions({
        url: this._getUploadUrl(options),
        customHeaders: { 'at': this.authService.getAuthToken() },
      });

      uploader._emitter.subscribe((data) => {
        if (data['done'] || data['abort'] || data['error']) {
          observer.next(data);
          observer.complete();
        }
      });

      uploader.addFilesToQueue([files[0]]);
    });
  }
开发者ID:KostyaDanovsky,项目名称:ng2-admin,代码行数:26,代码来源:fileHelper.service.ts

示例5: loginUser

	public loginUser(formData: {username: string, password: string}): Observable<any> {
		if (formData.username && formData.password) {
			return Observable.create((observer) => {
				this.http.post("http://localhost:8080/login", formData).subscribe((data: IUserToken) => {
					this.setUserToken(data);
					observer.next({success: this.getUserToken()});
				});
			});
		} else {
			return Observable.create((observer) => { observer.next({error: "Form not complete"})});
		}
	}	
开发者ID:vincentdu101,项目名称:FlagShip-Main,代码行数:12,代码来源:session.service.ts

示例6: it

  it('onDeleteSensor should delete the sensor', async(() => {
    spyOn(
      sensorParserConfigService,
      'deleteSensorParserConfig'
    ).and.returnValue(
      Observable.create(observer => {
        observer.next({});
        observer.complete();
      })
    );

    alerts.showSuccessMessage = jasmine.createSpy('showSuccessMessage');
    router.navigateByUrl = jasmine.createSpy('navigateByUrl');
    setDataForSensorOperation();

    component.selectedSensorName = 'abc';

    component.onDeleteSensor();

    expect(
      sensorParserConfigService.deleteSensorParserConfig
    ).toHaveBeenCalledWith('abc');
    expect(alerts.showSuccessMessage).toHaveBeenCalledWith(
      'Deleted sensor abc'
    );
    expect(router.navigateByUrl).toHaveBeenCalledWith('/sensors');
  }));
开发者ID:JonZeolla,项目名称:incubator-metron,代码行数:27,代码来源:sensor-parser-config-readonly.component.spec.ts

示例7:

export const childOf = (parentMessage: JupyterMessage) => (
  source: Observable<JupyterMessage>
) => {
  const parentMessageID = parentMessage.header.msg_id;
  return Observable.create((subscriber: Subscriber<JupyterMessage>) =>
    source.subscribe(
      msg => {
        // strictly speaking, in order for the message to be a child of the
        // parent message, it has to both be a message and have a parent to
        // begin with
        if (!msg || !msg.parent_header || !msg.parent_header.msg_id) {
          if (process.env.DEBUG === "true") {
            console.warn("no parent_header.msg_id on message", msg);
          }
          return;
        }

        if (parentMessageID === msg.parent_header.msg_id) {
          subscriber.next(msg);
        }
      },
      // be sure to handle errors and completions as appropriate and
      // send them along
      err => subscriber.error(err),
      () => subscriber.complete()
    )
  );
};
开发者ID:kelleyblackmore,项目名称:nteract,代码行数:28,代码来源:index.ts

示例8: getLocation

  /**
   * Obtains the geographic position, in terms of latitude and longitude coordinates, of the device.
   * @param {Object} [opts] An object literal to specify one or more of the following attributes and desired values:
   *   - enableHighAccuracy: Specify true to obtain the most accurate position possible, or false to optimize in favor of performance and power consumption.
   *   - timeout: An Integer value that indicates the time, in milliseconds, allowed for obtaining the position.
   *              If timeout is Infinity, (the default value) the location request will not time out.
   *              If timeout is zero (0) or negative, the results depend on the behavior of the location provider.
   *   - maximumAge: An Integer value indicating the maximum age, in milliseconds, of cached position information.
   *                 If maximumAge is non-zero, and a cached position that is no older than maximumAge is available, the cached position is used instead of obtaining an updated location.
   *                 If maximumAge is zero (0), watchPosition always tries to obtain an updated position, even if a cached position is already available.
   *                 If maximumAge is Infinity, any cached position is used, regardless of its age, and watchPosition only tries to obtain an updated position if no cached position data exists.
   * @returns {Observable} An observable sequence with the geographical location of the device running the client.
   */
  public getLocation(opts): Observable<any> {

    return Observable.create(observer => {

      if (window.navigator && window.navigator.geolocation) {
        window.navigator.geolocation.getCurrentPosition(
          (position) => {
            observer.next(position);
            observer.complete();
          },
          (error) => {
            switch (error.code) {
              case 1:
                observer.error(GEOLOCATION_ERRORS['errors.location.permissionDenied']);
                break;
              case 2:
                observer.error(GEOLOCATION_ERRORS['errors.location.positionUnavailable']);
                break;
              case 3:
                observer.error(GEOLOCATION_ERRORS['errors.location.timeout']);
                break;
            }
          },
          opts);
      }
      else {
        observer.error(GEOLOCATION_ERRORS['errors.location.unsupportedBrowser']);
      }

    });



  }
开发者ID:ia-studio,项目名称:kcg-online,代码行数:47,代码来源:geoLocation.service.ts

示例9: prerender

  prerender(options: PrerenderOptions = {pessimistic: false}): Observable<Snapshot<V>> {
    this.render.pessimistic = (options && options.pessimistic) || false;

    return Observable.create(async (observe) => {
      if (this.render.routes == null || this.render.routes.length === 0) {
        this.render.routes = renderableRoutes(await this.discoverRoutes());
      }

      this.render.routes = (this.render.routes || []).filter((r: Route & {server?: boolean}) =>
        r.server == null
          ? !this.render.blacklist
          : r.server);

      if (this.render.routes.length === 0) {
        observe.complete();
      }
      else {
        this.renderToStream(this.render)
          .subscribe(
            observe.next.bind(observe),
            observe.error.bind(observe),
            observe.complete.bind(observe));
      }
    });
  }
开发者ID:sonukapoor,项目名称:angular-ssr,代码行数:25,代码来源:application.ts

示例10: localSaveColores

 /**
  * Guarda los Colores en le cache local
  * 
  * @private
  * @param {Array<Color>} data
  * @returns {Observable<ResponseClass.Response> }
  * Exito: {Array<Color>}
  * Falla: Observable.error(error)
  */
 private localSaveColores(data: Array<Color>): Observable<ResponseClass.Response> {
   let response: ResponseClass.Response;
   return Observable.create(obs => {
     if (!this.db) { this.initDB(); }
     this.db.get('color').then(doc => {
       return this.db.put({
         _id: 'color',
         _rev: doc._rev,
         doc: data
       });
     }).then(res => {
       response = new ResponseClass.Response(true, ResponseClass.RES_OK, 'Datos actualizados correctamente');
       response.result = data;
       obs.next(response);
     }).catch(err => {
       this.db.put({
         _id: 'color',
         doc: data
       }).then(() => {
         response = new ResponseClass.Response(true, ResponseClass.RES_OK, 'Datos ingresados correctamente');
         response.result = data;
         obs.next(response);
       }).catch(err => {
         response = new ResponseClass.Response(false, ResponseClass.RES_LOCAL_STORAGE_FAIL, 'Error al guardar localmente');
         response.result = err;
         obs.error(response);
       })
     });
   });
 }
开发者ID:sclMAX,项目名称:INDUMATICS,代码行数:39,代码来源:colores.ts


注:本文中的rxjs.Observable.create方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。