getProfile(username) {
		this._profileUrl = "https://api.github.com/users/" + username;
		this._followersUrl = "https://api.github.com/users/" + username + "/followers";

		return Observable.forkJoin(
			this._http.get(this._profileUrl).map(res => res.json()),
			this._http.get(this._followersUrl).map(res => res.json())
		)
	}
 getImageIDs(ids) {
     console.log('ids', ids);
     var books = null;
     var movies = null;
     var obs: any[];
     obs = [];
     for (var i = 0; i < ids.length; i++) {
         obs.push(this.http.get(this.getPhotoURL(ids[i].id)).map((res: Response) => res.json()));
     }
     return Observable.forkJoin(obs);
 }
Example #3
0
  loadAll() {
    if (this._store.images.length > 0) return Observable.of(this._store.images);

    Observable.forkJoin(
      this._hat.getAllValuesOf('photos', 'dropbox')
        .map(data => data.map(this.imgMap)),
      this._hat.getAllValuesOf('metadata', 'dropbox_plug')
    ).subscribe(responses => {
      this._store.images = responses[0];
      this._authBearer = "Bearer " + responses[1][0]['access_token'];
      this.downloadImages();
    }, err => console.log('There was an error loading images from HAT', err));
  }
Example #4
0
 // forkJoin pattern    
 constructor5() {
     console.log(new Observable());
     
     var userStream = Observable.of({
         userId: 1, username: 'kling'
     }).delay(2000);
     
     var tweetStream = Observable.of([1,2,3]).delay(1500);
     
     var c = Observable.forkJoin(userStream, tweetStream)
         .map(joined => new Object({user: joined[0], tweet: joined[1]}));
     //c.subscribe(x => console.log(x));   
     c.subscribe(x => console.log(x));  
 }
Example #5
0
 ngOnInit() {
     let request = new Request({
         method: RequestMethod.Get,
         url: `https://api.github.com/repos/${this.organization}/${this.repo}/readme`,
         headers: new Headers({'Accept': 'application/vnd.github.full.html'})
     });
     Observable.forkJoin(
         this.http.request(request).map(res => res.text()),
         this.http.get(`https://api.github.com/repos/${this.organization}/${this.repo}/commits?per_page=25`).map(res => res.json())
     ).subscribe(res => {
         this.markdown = res[0];
         this.commits = res[1];
     });
 }
Example #6
0
    return Observable.create(observer => {

      Observable.forkJoin(
        that.getEndangeredMamals(),
        that.getEndageredBirds()
      ).subscribe(data => {
        list = data[0];
        list.push.apply(list, data[1]);

        observer.next(list);
        observer.complete();

      });
    });
Example #7
0
 startUpload(sessionId: string, file: any) {
   Observable.forkJoin(
     this.configService.getFileBrokerUrl(),
     this.createDataset(sessionId, file.name)
   ).subscribe((value: [string, Dataset]) => {
     const url = value[0];
     const dataset = value[1];
     file.chipsterTarget = `${url}/sessions/${sessionId}/datasets/${
       dataset.datasetId
     }?token=${this.tokenService.getToken()}`;
     file.chipsterSessionId = sessionId;
     file.chipsterDatasetId = dataset.datasetId;
     file.resume();
   }, err => this.restErrorService.showError("upload failed", err));
 }
Example #8
0
 private uploadUser(user: firebase.User): Observable<[User, UserPrivate]> {
   const platformUser = new User({
     $key: user.uid,
     displayName: user.displayName,
     photoURL: user.photoURL,
     updatedAt: firebase.database.ServerValue.TIMESTAMP,
   });
   const platformUserPrivate = new UserPrivate({
     $key: user.uid,
     email: user.email,
   });
   return Observable.forkJoin(
     this.userService.updateUser(platformUser),
     this.userPrivateService.updateUserPrivate(platformUserPrivate),
   );
 }
Example #9
0
 // catch observable error pattern    
 constructor6() {
     console.log(new Observable());
     
     var userStream = Observable.throw(new Error("Something failed"));
     
     var tweetStream = Observable.of([1,2,3]).delay(1500);
     
     var c = Observable.forkJoin(userStream, tweetStream)
         .map(joined => new Object({user: joined[0], tweet: joined[1]}));
         
     //c.subscribe(x => console.log(x));   
     c.subscribe(
         x => console.log(x),
         error => console.error(error)
         );  
 }
Example #10
0
    getData() {
      const countryDetails$ = this.countryDetailsService.getData(this.country, this.lang);
      const weather$ = this.weatherService.getData(this.lat, this.lng);
      const images$ = this.imagesService.getData(this.name);
      const countrydescription$ = this.countryDescriptionService.getData(this.name, this.lang);

      Rx.Observable.forkJoin([countryDetails$, weather$, images$, countrydescription$]).subscribe(
        res => {
          this.countrydetails = res[0].geonames[0],
          this.weatherdetails = res[1].weatherObservation,
          this.images = res[2].hits.length == 3 ? res[2].hits : null,
          this.countrydescription = res[3].geonames
        },
        err => console.log(err)
      );
      // TODO handle error
    }
Example #11
0
  ngOnInit() {
    console.clear();
    Observable.forkJoin(
      this.http.get('http://jsonplaceholder.typicode.com/todos').map(res => res.json()),
      this.http.get('https://jsonplaceholder.typicode.com/users').map(res => res.json())
    ).subscribe(
      data => console.log(data),
      err => console.error(err.message)
      );

    let p1 = this.http.get('http://jsonplaceholder.typicode.com/todos').map(res => res.json()).toPromise();
    let p2 = this.http.get('https://jsonplaceholder.typicode.com/users').map(res => res.json()).toPromise();

    Promise.all([p1, p2]).then(values => {
      console.log('Promise',values);
    })
  }
Example #12
0
                    .subscribe(prContainer => {
                        // get first page of pull requests
                        let pullRequests = prContainer.values;

                        // Calc number of other pages to get
                        let nbPages = Math.ceil(prContainer.size / prContainer.pagelen);

                        if (nbPages === 1) {
                            // Return the result to the observers
                            observer.next(pullRequests);
                        }

                        // Build array of fetch to subscribe
                        let fetchPages: any[] = [];
                        for (let i = 2; i <= nbPages; i++) {
                            fetchPages.push(this.fetchPullRequestPage(i));
                        }

                        // get synchrone result of all fetch
                        Observable.forkJoin(fetchPages).subscribe(datas => {
                            let dataArray: any = datas;
                            dataArray.forEach((data: any) => {
                                pullRequests = pullRequests.concat(data.values);
                            });

                            let modelPullRequests: PullRequest[] = pullRequests.map((pullRequest: any) => {

                                let modelPullRequest: PullRequest = {
                                    id: pullRequest.id,
                                    title: pullRequest.title,
                                    description: pullRequest.description,
                                    merge_commit: pullRequest.merge_commit,
                                    author: {userName: pullRequest.username,
                                             displayName: pullRequest.display_name,
                                             uuid: pullRequest.uuid},
                                    createdOn: new Date(pullRequest.created_on),
                                    updatedOn: new Date(pullRequest.updated_on),
                                    commentCount: pullRequest.comment_count
                                };
                                return modelPullRequest;
                            });
                            observer.next(modelPullRequests);
                        });

                    }, err => {
 this.dspaceService.createItem(this.item.sanitize(), token, currentContext.id).subscribe(response => {
     if(response.status == 200) {
         this.item.id = JSON.parse(response.text()).id;
         if(this.files.length > 0) {
             let bitStreamObservables = new Array<any>();
             for(let file of this.files) {
                 bitStreamObservables.push(this.dspaceService.addBitstream(this.item, file, token));
             }
             Observable.forkJoin(bitStreamObservables).subscribe(bitstreamResponses => {
                 this.finish(this.item.name, currentContext);
             },
             errors => {
                 this.finish(this.item.name, currentContext);
             });
         }
         else {
             this.finish(this.item.name, currentContext);
         }
     }
 },
 getAlbum(id) {
   return Observable.forkJoin(
     this.http.get(`api/albums/${id}`).map(res => res.json().album),
     this.http.get(`api/albums/${id}/tracks`).map(res => res.json().tracks)
   )
 }
Example #15
0
 // Uses Observable.forkJoin() to run multiple concurrent http.get() requests.
 // The entire operation will result in an error state if any single request fails.
 getBooksAndMovies() {
   return Observable.forkJoin(
     this.http.get('/app/books.json').map((res:Response) => res.json()),
     this.http.get('/app/movies.json').map((res:Response) => res.json())
   );
 }
Example #16
0
 retrievePeople() {
     return Observable.forkJoin(
         this.http.get('./app/people.json').map((res:Response) => res.json()),
         this.http.get('./app/people2.json').map((res:Response) => res.json())
         );
 };
    constructor() {
        // Test various forms of Observable.
        console.log("fromArray [1,2,3]");
        var observable = Observable.fromArray([1, 2, 3])
            .subscribe(x => console.log(x));

        console.log("of [1,2,3]");
        observable = Observable.of([1,2,3])
            .subscribe(x => console.log(x));

        console.log("of 1,2,3");
        observable = Observable.of(1,2,3)
            .subscribe(x => console.log(x));

        console.log("empty");
        observable = Observable.empty()
            .subscribe(x => console.log(x));

        console.log("range 1,5");
        observable = Observable.range(1,5)
            .subscribe(x => console.log(x));

        console.log("completion function");
        observable = Observable.of(1)
            .subscribe(
                x => console.log(x),
                err => console.error(err),
                () => console.log("completed")
            );


        // console.log("interval 1000");
        // var interval = Observable.interval(10000)
        //     .flatMap(x => {
        //         // call server
        //         return Observable.of([1,2,3]);
        //     })
        //     .subscribe(x => console.log(x));

        // Simulating error.
        console.log("error handling");
        var errObs = Observable
            .throw(new Error("ahh!"))
            .subscribe(
                x => console.log(x), // success
                err => console.error(err) // error
            );

        // simulate a call which fails twice then succeeds.
        console.log("error handling with retry");
        var counter = 0;
        var ajaxCall = Observable.of('url')
            .flatMap(() => {
                if(++counter < 2)
                    return Observable.throw(new Error("ahh!"));

                return Observable.of([1,2,3]);
            })
            .retry(3)
            .subscribe(x => console.log(x), err => console.error(err));

        console.log("error handling with catch");
        var catchObs = Observable
            .throw(new Error("ahh!"))
            .catch(err => {
                return Observable.of([1,2,3]);
            })
            .subscribe(x => console.log(x));

        console.log("timeout");
        var timeout = Observable
            .of([1,2,3])
            .delay(5000)
            .timeout(100)
            .subscribe(x => console.log(x), err => console.error(err));

        // join two observables. Returns an array of the results
        // [o1.results, o2.results] after both complete. Map to something nicer.
        console.log("forkJoin");
        var o1 = Observable.of({
            userId: 1,
            username: 'something'
        }).delay(2000);
        var o2 = Observable.of([1,2,3]).delay(1500);
        Observable
            .forkJoin(o1,o2)
            .map(data => {
                {
                    return {
                        user: data[0],
                        stream: data[1]
                    };
                }
            })
            .subscribe(x => console.log(x));
    }
Example #18
0
 getArts() {
    return Observable.forkJoin(
        this.http.get('./app/ars.data.json').map((res:Response) => res.json()));
 }
Example #19
0
 observable1 = constructorZone1.run(() => {
   return Rx.Observable.forkJoin(Rx.Observable.range(1, 2), Rx.Observable.from([4, 5]));
 });
 .flatMap(poste => (
   Rx.Observable.forkJoin([
     Rx.Observable.fromPromise(getHtml(poste.link)),
     Rx.Observable.of(poste)
   ])
 ))
    constructor(fb:FormBuilder) {
        this.formModel = fb.group({
            search: []
        });

        var searchControl = this.formModel.find('search');
        searchControl.valueChanges
            .debounceTime(400)
            .map(str => (str.replace(' ', '-')))
            .subscribe(x => console.log(x));


        /** travel search */
        var startDates = [];
        var startDate = new Date();

        for (var day = -2; day < 2; day++) {
            var date = new Date(
                startDate.getFullYear(),
                startDate.getMonth(),
                startDate.getDate() + day
            );
            startDates.push(date);
        }

        Observable
            .fromArray(startDates)
            .map(date => {
                console.log("Getting deals for date: " + date);
                return [1, 2, 3];
            })
            .subscribe(x => console.log(x));

        /** interval */
        // Observable
        //     .interval(1000)
        //     .subscribe(x => console.log(x))

        // Observable
        //     .interval(1000)
        //     .flatMap(x => {
        //         console.log("Calling server to get latest news..");
        //         return Observable.of([1, 2, 3]);
        //     })
        //     .subscribe(news => console.log(news));

        /** delay */
        var userStream = Observable.of({
            userId: 1, userName: 'chanu'
        }).delay(2000);

        /** join */
        var tweetsStream = Observable.of([1, 2, 3]).delay(1500);

        Observable
            .forkJoin(userStream, tweetsStream)
            .map(joined => Object({user: joined[0], tweets: joined[1]}))
            .subscribe(result => console.log(result));

        /** error handling */
        var observable = Observable.throw(new Error("Something failed!"));
        observable
            .subscribe(
                x => console.log(x),
                error => console.log(error));

        /** retry */
        var counter = 0;
        var ajaxCall = Observable
            .of('url')
            .flatMap(() => {
                if (++counter < 2)
                    return Observable.throw(new Error("Request failed!"));
                return Observable.of([1, 2, 3]);
            })
            .retry(3)
            .subscribe(
                x => console.log("Response from retry: " + x),
                error => console.log(error)
            );

        /** catching and continuing */
        var remoteDataStream = Observable.throw(new Error("Something is wrong!"));
        remoteDataStream.catch(err => {
                var localDataStream = Observable.of([1, 2, 3]);
                return localDataStream;
            })
            .subscribe(x => console.log("Catching and continuing: " + x));

        /** Completed */
        Observable
            .throw(new Error("error"))
            .subscribe(
                x => console.log(x),
                error => console.log(error),
                () => console.log("Completed"));

        Observable
            .fromArray([1, 2, 3])
            .subscribe(
                x => console.log(x),
                error => console.log(error),
                () => console.log("Completed"));


    }
 /**
 * Observable.forkJoin : along the lines of $q.all... Remember to import it!
 */
 getAllArtist(artist: string = 'The Cure', options: any = {}, optionsAlbums: any = {}) {
     return Observable.forkJoin(
         this.getArtistInfo(artist, options),
         this.getTopAlbums(artist, optionsAlbums)
     );
 }
Example #23
0
 loadOffer(uuid: string): Observable<any> {
   return Observable.forkJoin(
     this._marketSvc.getOffer()
       .map((marketOffers: Array<any>) => marketOffers.find(offerItem => offerItem.offer.uuid === uuid))
   );
 }