代码之家  ›  专栏  ›  技术社区  ›  si2030

Aurelia-导航菜单未根据@计算值更新

  •  0
  • si2030  · 技术社区  · 7 年前

    我收到并回复 THIS

    这是我的导航菜单-我希望“loggedIn”为true,如果它在本地存储中有值。。。

            <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>
    

    这是导航菜单。ts viewmodel显示@computedFrom和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()
                }
            }
    

    这是我的loggedIn类-非常简单-关闭并在本地存储中获取一个值-如果不在那里,则返回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;
              }
            }
    

    没有我的控制台。控制台中会显示日志,这意味着这些函数都没有被命中。。我不知道为什么。。应该很简单。。

    有人可以看看这个,并告诉我为什么它仍然不工作?

    更新

    我感谢Jeremy的关注,我已经尝试过实现这一点。这是我更新的课程。

    我已经更改了课程的名称,但它们代表了Jeremy的建议。在这里,他们的顺序是一样的,他提出了他们。。。

    这是我对他的“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”,将“username”设置为“匿名”。

    这是我的“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) { }
        }
    

    我想这应该给我的导航菜单。html-视图-访问这些值,在这里我不确定在if中应该如何访问它们。绑定我只是想用以下方法进行测试:

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

    最后,这是我的auth\u服务版本。ts.这是进行抓取以登录的地方-我已经在抓取中设置了loggedIn和username的值:

        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视图中仍然没有任何活动。。不确定我是否设置好了,想知道是否有人可以再看一眼。。也许我没有在导航栏视图中正确引用它。我注意到loggedInService在navmenu和login中都是一个依赖项。ts视图模型。这不是工作吗,或者把事情搞砸了。。。。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Jeremy Danyow    7 年前

    您可以稍微不同地对此进行建模,并避免所有肮脏的检查和computedFrom。

    为当前用户创建模型:

    使用者输电系统

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

    然后依赖于需要访问 isLoggedIn 说明或用户的详细信息:

    导航菜单。输电系统

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

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

    身份验证服务。输电系统

    @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;
             ...
          });
      }
    }
    
        2
  •  0
  •   bigopon    7 年前

    这可能是因为您根本没有使用视图模型。尝试检查您是否参考了模块导航菜单视图模型或其视图 navmenu.html