logo
down
shadow

How to check if a RxJS Observable contains a string in Angular2?


How to check if a RxJS Observable contains a string in Angular2?

Content Index :

How to check if a RxJS Observable contains a string in Angular2?
Tag : angular , By : rhinojosa
Date : December 05 2020, 12:23 PM

wish help you to fix your issue Observables are asynchronous so you can't use let getRoles = ...map(...). The map() method is not executed on an array but on an Observable which is always asynchronous.
So proper way to do it could be (I didn't test this code):
public hasRole(name: string): Observable {
    return this.tokenService.getTokenInformation()
        .map(element => element.roles)
        .first(roles => roles.indexOf(name) !== -1);
}
hasRole('my-role').subscribe(
    role => console.log("has role"),
    error => console.log("doesn't have role"),
)
public hasRole(name: string): Observable {
    return this.tokenService.getTokenInformation()
        .map(element => element.roles)
        .first(roles => roles.indexOf(name) !== -1, undefined, false)
        .map(val => !!val);
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Angular2 rxjs/Subject , rxjs/Observable events not working across the parent and child router


Tag : javascript , By : Mahesh
Date : March 29 2020, 07:55 AM
Hope that helps Ensure you have GlobalService only provided once at the root component. If you add it to providers of every component where you use it, each component gets it's own instance and if one subscribes its a different instance then where events are emitted and therefore doesn't get notified.
Angular2 DI maintains a single instance per provider

Cancel observable after first time - Angular2, TypeScript, rxjs/Observable


Tag : typescript , By : Ben Brown
Date : March 29 2020, 07:55 AM
I wish this help you Have you tried first() instead of take(1)
Depending on your imports at the module level, you may want to add an import for the first operator
import 'rxjs/add/operator/first'
let subscription = this.auth.getUserData().take(1).subscribe(data => { // the take(1) doesn't work
  console.log('Firebase responded with success.');
  this.rootPage = TabsPage;
  subscription.unsubscribe();
 }, err => {
  console.log('Firebase responded with error.', err);
  this.rootPage = LoginEmailPage;
 }
);

Can not filter RxJS Observable on Angular2


Tag : angular , By : Debashree
Date : March 29 2020, 07:55 AM
I hope this helps you . Try with the following to apply filter :
Change your service as below :
getPlayers(position: string) {
    return this.get(`players/${position}`)
        .map(r => r.json())
        .catch(error => {
            console.log('Error: ', error);
            return [];
        });
}
players: Player[];

//Call your service to get data and remove async pipe from HTML
this.svc.getPlayers(this.position).subscribe(res => {
  this.players = (res.data.length) ? res.data.filter(p => p.position === 'hq'):[];
});

Angular2 rxjs sort (observable) list of objects by an observable field


Tag : angular , By : Matt Logan
Date : March 29 2020, 07:55 AM
will be helpful for those in need for clarifying the question, Phosphoros. :)
Here's how you could do what you asked:
// Function to compare two objects by comparing their `unwrappedName` property.
const compareFn = (a, b) => {
  if (a.unwrappedName < b.unwrappedName)
    return -1;
  if (a.unwrappedName > b.unwrappedName)
    return 1;
  return 0;
};

// Array of Thing objects wrapped in an observable.
// NB. The `thing.name` property is itself an observable.
const thingsObs = Observable.from([
  { id: 1, name: Observable.of('foo') },
  { id: 2, name: Observable.of('bar') },
  { id: 3, name: Observable.of('jazz') }
]);

// Now transform and subscribe to the observable.
thingsObs

  // Unwrap `thing.name` for each object and store it under `thing.unwrappedName`.
  .mergeMap(thing =>
    thing.name.map(unwrappedName => Object.assign(thing, {unwrappedName: unwrappedName}))
  )

  // Gather all things in a SINGLE array to sort them.
  .toArray()

  // Sort the array of things by `unwrappedName`.
  .map(things => things.sort(compareFn))

  .subscribe();
[
  { id: 2, name: ScalarObservable, unwrappedName: "bar" },
  { id: 1, name: ScalarObservable, unwrappedName: "foo" },
  { id: 3, name: ScalarObservable, unwrappedName: "jazz" }
]

Check condition of Observable and execute/return function (angular2, rxjs)


Tag : javascript , By : drbillll
Date : March 29 2020, 07:55 AM
Any of those help You can use the mergeMap( flatMap is the rxjs4 alias) operator for this:
getData() {
// check source of data to return...
   return this.hasLocal().mergeMap((res) => {
        if (res === 0) // no data in storage
            return this.getRemote(); // <-- I want to return this
        else
            return this.getLocal(); // <-- or this to the component.
    })
}
Related Posts Related QUESTIONS :
  • The fields in my form are not binding to the model attributes in Angular
  • Can someone help me out here, can't get the routing to work properly, keep getting 404
  • Providing/Injecting third party service to component while angular component unit testing
  • Using Reactive Forms to send value from field wrapped in compulsory object
  • how to get http response from typescript post
  • how to get public IP in Angular Project
  • Access Nested Models from function Angular
  • Angular 7 - Set the data source for the Select/dropdown box
  • Angular Material Dialogue issue - Error: The selector "dialog-result-example-dialog" did not match any element
  • BodyParser doesn't parse - but everything looks right to me. How to resolve `Cannot read property of undefined`
  • Deep Linking with IOS and Android Nativescript
  • Angular 8 + IE 11: Some polyfills are missed
  • How access form attributes from component?
  • Pass all FromGroup control values to another FormGroup
  • In Angular 7, how do I access the component that emitted an event?
  • Not able to call a method when a feature/marker is selected in OpenLayers
  • How to Implement Nested NG If else conditions in Angular 8
  • Want only single true or false value from observers
  • How to add react custom element in angular 6
  • StaticInjectorError(AppModule)[MainComponent -> MatDialog]
  • Loop through data set showing undefined
  • Why does the Angular Material table mat-paginator pagesize not work?
  • Can Web API get input from angular client for confirmation and continue execution?
  • Will the angular build include the spec file size?
  • Meta tags angular 7
  • Can't find file on stackblitz Angular project
  • AngularFire Auth exchange FireBase token for my platform's token before re-direct
  • Angular 8 Component / Service: How to retrieve data from async function in service
  • Add a control to a dynamic Angular reactive form
  • Looking to Add Role-Based Authentication System
  • Angular 7/8, 1 dependency is interfering with another one, How to avoid the loading of a deep dependency while inside a
  • Compiler errors (resolving) when compiling after addition of Firebase Admin SDK
  • wrapper observable event on top of http call
  • Nginx container does not send requests to back-end
  • ngOnInit starts before APP_INITIALIZER is done
  • How to trigger a data service call in Angular
  • Where do I declare my external service in my app.module.ts file?
  • event propagation cdk drag
  • use argument as object property in angular
  • How to create new object in redux selector and return it
  • How can I show my own text status before i switch my toggle button while using mat-slide-toggle
  • Get the API response and store the data in to an array
  • How to obtain previous and new value from Angular mat-select?
  • Send payload data with POST/PUT/PATCH requests to Sentry.io
  • Angular 8 not working in IE 11 and Safari browser
  • How to create function name from json in Angular 7
  • Im trying to push values from an array with objects to another array with objects
  • Got an error when I add "changeDetectionStrategy" to my app
  • Angular typescript object undefined at start leading to undefined error
  • Failed: Template parse errors: There is no directive with "exportAs" set to "bsDatepicker" while run
  • Error: Can't resolve all parameters for setupPlatform: (?, [object Object], [object Object])
  • Differences between ng build and ng build --watch
  • Does an angular component ever destroy when it is subscribed to router change event once?
  • How do I get the JSON response from httpModule.get?
  • Ngx-logger implementation in angular 8
  • font size increase decrease by button using angular 7
  • Are selectors and module declarations mandatory for components?
  • Why angular is adding '#' in each route?
  • how to block the subsequent clicks in angular?
  • Ionic Angular TypeError: architect_1.createBuilder is not a function
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com