Aurelia-Navmenu不基于@compute值更新 [英] Aurelia - Navmenu not updating based on @computed value

查看:62
本文介绍了Aurelia-Navmenu不基于@compute值更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到了这个问题的问题并回答了该问题,我认为这是正确的,但是我没有得到传播回该问题的价值.看法.我添加了许多console.logs,它们没有被击中.

I received and answer from THIS question which I think is correct however I do not get a value propagating back to the view. I have added in a number of console.logs and they are not being hit.

这是我的navMenu-我希望"loggedIn"为true,如果它在localstorage中具有值...

Here is my navMenu - I wanted "loggedIn" to be true if it has a value in localstorage...

        <template bindable="router">
        <require from="./navmenu.css"></require>
        <div class="main-nav">
            <div class="navbar navbar-inverse">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="#/home">Jobsledger.API</a>
                </div>
                <div class="navbar-collapse collapse">

                    <ul class="nav navbar-nav">

                        <li repeat.for="row of router.navigation" class="${ row.isActive ? 'link-active' : '' }">
                            <a href.bind="row.href" if.bind="loggedIn">${ row.title }</a>

                            <a href.bind="row.href" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"
                               if.bind="loggedIn">
                                ${row.title}
                                <span class="caret"></span>
                            </a>

                            <ul if.bind="loggedIn" class="dropdown-menu">
                                <li repeat.for="menu of row.settings.nav">
                                    <a href.bind="menu.href">${menu.title}</a>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
        test ${loggedIn}
    </template>

这是navmenu.ts视图模型,显示了@computedFrom和getter:

Here is the navmenu.ts viewmodel showing the @computedFrom and the getter:

            import { autoinject, inject, NewInstance } from "aurelia-framework";
        import { computedFrom } from "aurelia-binding";
        import { bindable } from "aurelia-templating";

        import { LoggedInService } from "../components/auth/LoggedInService";

        @autoinject
        export class Navmenu {
            constructor(private testAuthentication: LoggedInService) {
                console.log("loggedin value: ", this.testAuthentication.isAuthenticated())
            }

            @computedFrom('testAuthentication.authenticated')
            get loggedIn() {
                console.log("loggedin value: ", this.testAuthentication.isAuthenticated())
                return this.testAuthentication.isAuthenticated()
            }
        }

这是我的登录类-非常简单-关闭并获取本地存储中的值-如果不存在则返回false.

Here is my loggedIn class - pretty simple - goes off and gets a value in local storage - if its not there it returns false.

         export class LoggedInService {
          private LOGGED_IN = "loggedIn";
          constructor() {}

          isAuthenticated(): boolean {
            var authenticated = localStorage.getItem(this.LOGGED_IN);

            console.log("LOGGEDIN - typeof: ", authenticated);

            if (authenticated != null) {
              return true;
            } else return false;
          }
        }

我的console.logs都没有显示在控制台中,这意味着这些功能都没有被击中..我不知道为什么..应该很简单..

None of my console.logs are displayed in the console which means none of those functions are being hit.. I dont know why.. should be pretty simple..

有人可以看看这个,并指导我为什么它仍然不起作用吗?

Could someone have a look over this and direct me to why its still not working?

更新

我非常感谢Jeremy的关注,并且我已经努力实现了这一目标.这是我更新的课程.

I appreciate Jeremy taking a look and I have had a go at implementing this. Here are my updated classes.

我更改了班级的名称,但它们代表了杰里米的建议.在这里,它们的顺序与他向他们展示的顺序...

I have changed the names on the classes but they represent what Jeremy has suggested. Here they are in the same order he presented them...

这是我的"user.ts"版本:

Here is my version of his "user.ts":

        export class LoggedInService {
        private LOGGED_IN = "loggedIn";

        isLoggedIn: boolean = false;
        userName: string = 'anonymous';

        constructor() { }

        isAuthenticated(): boolean {
            var authenticated = localStorage.getItem(this.LOGGED_IN);

            console.log("LOGGEDIN value HERE!: ", authenticated);

            if (authenticated != null) {
                return true;
            } else {
                return false;
            }
        }
    }

我将"isLoggedIn"设置为"false",用户名"设置为"anonymous".

I have "isLoggedIn" set as 'false' and "username" set to 'anonymous'.

这是我的"navmenu.ts"版本:

Here is my version of "navmenu.ts":

    import { autoinject } from "aurelia-framework";
    import { bindable } from "aurelia-templating";
    import { LoggedInService } from "../components/auth/LoggedInService";

    @autoinject
    export class Navmenu {

        constructor(public loggedInService: LoggedInService) { }
    }

我认为这应该给我的navmenu.html(视图)访问这些值的权限,在这里我不确定应如何在if.bind中访问它们.我只想使用以下方法进行测试:

I assume this should give my navmenu.html - the view - access to those values and here I am uncertain how they should be accessed in the if.bind. I just wanted to test it using:

 <div if.bind="loggedInService.isLoggedIn">
        working
    </div>

这没用.

最后这是我的auth_service.ts版本.这是进行提取的登录位置-我已在提取中设置了loggingIn和用户名的值:

Finally here is my version of auth_service.ts. This is where the fetch is undertaken to login - I have set the value of loggedIn and username in the fetch:

    constructor(
    private login: userLogin,
    private loggedinService: LoggedInService,
    private tokenService: TokenService,
    private userService: UserService,
    private router: Router,
    private http: HttpClient,
    private controllerFactory: ValidationControllerFactory
) {
    this.router = router;
    this.controller = controllerFactory.createForCurrentScope();
    this.controller.addRenderer(new BootstrapFormRenderer());


    // Check if user is logged in
    if (this.loggedinService.isAuthenticated()) {
        loggedinService.isLoggedIn = true;
        loggedinService.userName = this.userService.getUserName();
    }
}

submitLogin() {
    if (this.controller.validate()) {
        // Lets do a fetch!

        this.login.Username = this.username;
        this.login.Password = this.password;

        const task = fetch("/api/jwt", {
            method: "POST",
            body: JSON.stringify(this.login),
            headers: new Headers({ 'content-type': 'application/json' })
        })
            .then(response => response.json())
            .then(data => {
                // First save the JWT and as well save it to loggedInService.
                this.loggedinService.isLoggedIn = this.tokenService.saveJWT(data);

                // Next go back to the api and get the username and save that to loggedInService also.
                this.loggedinService.userName = this.userService.saveUserName();

                // Finally redirect to home page.
                this.router.navigate("home");
            })
            .catch(error => {
                this.tokenService.clearJWT();
            });
    }
}

我在navmenu视图中仍然没有任何活动..不确定是否设置了此功能,想知道是否有人可以对此进行其他查看..也许我没有在navbar视图中正确引用它.我注意到,loginInService在navmenu和login.ts视图模型中都是一个依赖项.不应该做这项工作或搞砸了....

I still dont get any kind of activity in the navmenu view.. not sure if I have set this ok wondering if someone can take another look at this.. maybe I havent referenced it correctly in the navbar view. I note that loggedInService is a dependency both in the navmenu and also the login.ts viewmodels. Shouldnt this work or have screwed something up....

推荐答案

您可以对此建模稍有不同,并避免所有脏检查和computeFrom内容.

You could model this slightly differently and avoid all the dirty checking and computedFrom stuff.

为当前用户创建模型:

user.ts

export class User {
  isLoggedIn = false;
  name = 'anonymous';
}

然后在需要访问isLoggedIn状态或用户详细信息的视图模型中依赖用户:

Then take a dependency on the user in view models that need access to the isLoggedIn state or the user's details:

navmenu.ts

@autoinject
export class Navmenu {
  constructor(public user: User) { }
}

执行登录工作或本地存储工作的服务也依赖当前用户,并在登录状态更改时更新其属性.

Services that do the login work or the local storage work also take a dependency on the current user, updating it's properties when the login state changes.

auth-service.ts

@autoinject
export class AuthService {
  constructor(private user: User) { 
     if (... check local storage, etc ... ) {
       user.isLoggedIn = true;
       user.name = ....
     }
  }

  login(username, password) {
    return fetch('/api/login', { method: 'POST', body: { ... } })
      .then(result => {
         ... 
         ...
         this.user.isLoggedIn = true;
         this.user.name = username;
         ...
      });
  }
}

这篇关于Aurelia-Navmenu不基于@compute值更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆