logo
Tags down

shadow

Rxjs Transform API result Observable to another Observable in a service function


By : Tony
Date : September 17 2020, 12:00 AM
it should still fix some issue I have a loader service whose result is Observable which contains a CSV file. Each row represent a different entity of (e.g.) Person object, the comma separated parts represent the property of the person for example id, age, name, etc. , map operator is your friend. Try like this:
code :
loadAllPerson(): Observable<Person[]> {
  return loadTextFile(PATH).pipe(
    map((csv: string) =>
      csv.split('\n')
         .map((rows: string[]) => rows.map((row: string) => row.split(',')))
         .map((table: string[][]) => 
           table.filter((cols: string[]) => !Number.isNaN(+cols[0]) && !Number.isNaN(+cols[3]))
                .map((cols: string[]) => new Person(+cols[0], cols[1], cols[2], +cols[3], cols[4], cols[5], cols[6], cols[7], new Date(cols[8])))
         )
    )),
  );
}


Share : facebook icon twitter icon

Pass result of one RxJS observable into next sequential observable


By : DHANUSH
Date : March 29 2020, 07:55 AM
hope this fix your issue The problem is in createAndUpload where map just turns the result from the first call into an Observable but you never subscribe to it.
So simply said you just need to use mergeMap (or concatMap in this case it doesn't matter) instead of map. The mergeMap operator will subscribe to the inner Observable and emit its result:
code :
createAndUpload(itemData, file): Observable<any> {
  return createItem(itemData, file)
    .mergeMap((res) => {
      if (file) {
        return addFileToItem(res.id, file);
      }
      return Observable.empty(); // you can't return `undefined` from the inner Observable
    });
}

How to chain the result of observable to the below observable in rxjs


By : user2819282
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I am saving user in the database. , I solved my issue using flatMap operator
code :
createUser(req: Request, res: Response): Observable<mongoose.Document> {
    const body = req.body
    const self = this

    const errorMessage = new UserValidator(req).validateRequest()
    if (errorMessage) {
        return throwError(errorMessage)
    } else {
        return self.hashPassword(req.body.password)
        .pipe(flatMap((hashedString) => {
            const newUser = new this.userModule({ email: req.body.email, username: req.body.username, password: hashedString })
            return this.save(newUser)
        }), catchError((err) => throwError(err))
    }
}

Return result directly from http (observable) service (function) without returning Observable


By : user3294685
Date : March 29 2020, 07:55 AM
like below fixes the issue You could try something like this:
I've included both the promise route (at the bottom) and the observable route
code :
GetDataEitherFromApiOrFromLocalStorage(): Observable<any> {
    return this.http.get('https://' + this.url + '/api/main/apidata').pipe(
        catchError((error) => {
            // Evaluate if error is fatal or expected
            errorIsNotFatal = true;
            if (errorIsNotFatal) {
                return this.localdata(); // this should return an observable;
            }
            return throwError(error);
        })
    );
}
        catchError((error) => {
            // Evaluate if error is fatal or expected
            errorIsNotFatal = true;
            if (errorIsNotFatal) {
                return this.localdata(); // this should return an observable;
            }
            return throwError(error);
        })
localdata(): Observable<any> {
    return of('anything or any kind of data');
}
export class SomeComponent implements OnInit {
    public data: any;

    constructor(private service: SomeService) {
    }

    ngOnInit() {
        this.service.GetDataEitherFromApiOrFromLocalStorage().subscribe((response) => {
            this.data = response;
        });
    }
}
GetDataEitherFromApiOrFromLocalStorage(): Promise<any> {
    return new Promise((resolve, reject) => {
        this.http.get("https://" + this.url + "/api/main/apidata").subscribe(
            (next) => { resolve(next); },
            (error) => { reject(error); }
        );
    });
}

RxJS Observable result from an Observable's output


By : user3573911
Date : March 29 2020, 07:55 AM
like below fixes the issue You can use a switchMap or mergeMap (also known as flatMap) operator.
Here's a good explanation about the difference between both: https://javascript.tutorialhorizon.com/2017/03/29/switchmap-vs-flatmap-rxjs/
code :
    addArticleToBookmarks(article: Article): Observable<SaveResponse> {
        return this.storageService.getBookmarkedArticles().pipe(
            switchMap(articles => {
                articles.push(article);
                return this.storageService.saveBookmarkedArticles(articles)
            })
        );
    }

Angular js 2 'node_modules/rxjs/Observable"' has no exported member 'Observable'. import Observable


By : sollune
Date : March 29 2020, 07:55 AM
I hope this helps . I am Getting below Error in Auth.d.ts file in Node_Modules Package. , Try changing it to:
code :
import { Observable } from 'rxjs';
Related Posts Related Posts :
  • How to let know typescript compiler about jest custom matchers?
  • TypeScript Compiler API function which can check if a class implements an interface
  • typescript currying call results and function definition
  • How would I enforce at-least one in many optional properties for a TypeScript interface?
  • Parameters generic of overloaded function doesn't contain all options
  • What is the benefit of union types in Typescript
  • Type inference with generic array in Typescript
  • Why TS is unsafe in unary arithmetic operations but not in binary ones?
  • Why does TS let me return wrong type in overloaded function declarations?
  • How do I tell TypeScript that interface T is narrower than type U which has an index signature?
  • Why doesn't TypeScript type guard 'in' narrows types to keyof types?
  • Typescript dynamically visible class methods
  • Why we need @types in TypeScript
  • a number between 0 and 1 as a type in typescript
  • Generic pattern-matching for tagged unions
  • NullInjectorError: StaticInjectorError(BootModule)[BsDropdownDirective -> AnimationBuilder]: NullInjectorError: No pr
  • Observable nested callbacks
  • Conditionally casting the input to a Typescript function
  • How do I connect express to vue app with axios
  • Simple import statements for npm package
  • React Native with typescript unable to resolve modules
  • Conditional response type
  • Typescript abstract property
  • typescript instanceof return false
  • How can I type a function that takes an arbitrary number of input functions such that its return type can be determined?
  • Acessing type as object or Array in Typescript
  • Operator '+' cannot be applied to types 'T' and 'T'. in TypeScript
  • Type is changing in TypeScript
  • Discriminate union types
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk