Angular 2 using Angular Cli and Ui Router Ng2, Resolve / Reject

I have a question for you guys. I am using Angular 2 configured with Angular -CLI with UiRouter (ui-router-ng2). All this is fantastic, and I am making progress. But I ran into a problem, I'm sure it is easily solvable, I just don’t know how to do it.

So, I have a “menu service” that grabs the categories from mock db that I configured. The service works great, and I can list the categories and use these categories to get subcategories and items. I am using URL-less parameters, i.e. I declare them as objects and pass them using [UiParams]. All this works well, and I can even use the "uiSref =" ^ "button to return to the parent state. Everything is great. BUT! For testing purposes, I use ui-router-visualizer, and I ran into a problem when I can still go to the state, although the object is empty. See, In my opinion, the object is allowed and returned empty. This prevents errors, of course, but if the user magically falls into a subordinate state, an empty object is placed in it, then nothing is displayed.This leads to errors in its own right, since the view has nothing to interpolate. This also causes the back button to malfunction, since ui-params are not available.

Now, all that is said, how can I reject a state transition if the returned object from my menu service is empty?

CODE For condition. For this I use Ng2StateDeclaration.

{
    name:'category',
    parent:'main.categories',
    params:{
        categoryid:{}
    },
    views:{
        '$default@main': { component: SubcategoryComponent },
        receipt: { component: ReceiptComponent }
    },
    resolve:[
        {
            token:'category',
            deps: [Transition, MenuService],
            resolveFn: (trans, menuSvc) => {
                menuSvc.getCategory(trans.params().categoryid)
            }

        }
    ]
}`

Here is the code for the menu service as a whole. It is super easy.

import { Injectable, Inject } from '@angular/core';
import { Headers, Http, Response} from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class MenuService {

constructor(@Inject(Http) public http:Http) { }

getCategories() {
    return this.http.get('api/menu')
            .map(this.extractData)
            .toPromise();

}
private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
}
getCategory(id){
    console.log(id);
    return this.getCategories()
        .then(cats => cats.find(cat => cat.id == id));
}
}

And also the component is also very simple. I use their quickstart app as my primary learning tool.

import { Component, Input, Inject } from '@angular/core';

@Component({
  templateUrl: './subcategory.component.html',
  styleUrls: ['./subcategory.component.css'],
    inputs: ["category"],
})
export class SubcategoryComponent {

category;
}

If someone can point me somewhere that answers this question, or tell me where and how to put in an If / Else statement that returns either an object or rejects a state transition, that would be awesome. I also structure things like the quickstart example, so all this is placed in a separate module from the main application module.

, , , -, .

!

+4
2

, , , , ?

, . getCategory , ( ), , .

:

const rejectWhenEmpty = (val) =>
    val ? val : Promise.reject('value is empty)

, ,

        resolveFn: (trans, menuSvc) =>
            menuSvc.getCategory(trans.params().categoryid).then(rejectWhenEmpty)

:

getCategory(id){
    return this.getCategories()
        .then(cats => cats.find(cat => cat.id == id))
        .then(rejectWhenEmpty);
}
+2

, . , . .

StateService ui-router-ng2

import {Ng2StateDeclaration,Transition, StateService} from 'ui-router-ng2';

, trans.from() .then

deps: [Transition, MenuService, StateService],
            resolveFn: (trans, itemSvc, $state) => {
                return itemSvc.getItems(trans.params().groupid).then(items =>{
                    return stateContinue(items, $state, trans.from());
                })
            }

function stateContinue(thing, $state, from){
if (!isEmpty(thing)){
    return thing;
}else {
    $state.go(from);
}}

, "" , "". / .

isEmpty

function isEmpty(obj) {
if (obj == null) return true;
if (obj.length > 0)    return false;
if (obj.length === 0)  return true;
if (typeof obj !== "object") return true;
for (var key in obj) {
    if (hasOwnProperty.call(obj, key)) return false;
}

return true; }

is-empty-object q/a

, - , . , , .

!

+1

Source: https://habr.com/ru/post/1658276/


All Articles