如何重新加载/刷新angular2中的所有当前组件? [英] How to reload/refresh all the current components in angular2?

查看:107
本文介绍了如何重新加载/刷新angular2中的所有当前组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用angularjs2的新alpha组件路由器 https://angular .io/docs/ts/latest/guide/router.html

Hi I am using the new alpha component router of angularjs2 https://angular.io/docs/ts/latest/guide/router.html

我有一个模式,该模式可对用户进行身份验证,然后在本地存储中创建一个JWT,该JWT包含用户所需的信息.

I have a modal that authenticate a user then creates a JWT in localstorage which holds the user's needed info.

我的问题是,如果用户在/home路径上查找,则只有登录用户才能看到某些内容,但是在通过模式登录后,他必须刷新页面,以便组件可以刷新并显示正确的登录信息

My problem is that if the user is looking on the /home path there are stuff there that only visible to logged-in users, but after he log in through the modal he has to refresh the page so the components will refresh and show the correct logged-in information

有没有办法告诉angular2刷新当前路径上的所有组件?就像重新加载页面一样,却没有真正重新加载整个页面(我不想只为用户点击刷新按钮)

Is there a way to tell angular2 to refresh all the components on the current path? like a page reload but without really reloading the whole page (I dont want to just hit the refresh button for the user)

预先感谢

当我尝试重定向到我已经进入的路线时,也许有一项功能可以强制重定向?

maybe there is a feature to FORCE REDIRECT when I try to redirect into a route I am already in?

尝试观察值

@Injectable()
export class UserService {
  private loggedInObservable;

    constructor(private http: Http) {
        this.loggedInObservable = Observable.of(this.checkIsLoggedIn());
    }

    checkIsLoggedIn() {
        let isLoggedIn = false;
        try {
            isLoggedIn = tokenNotExpired();
        } catch(e) {

        }
        console.log('returning:', isLoggedIn);
        return isLoggedIn;
    }


    login(model, cbSuccess=null, cbError=null, cbAlways=null) {
        serverPost(this, '/api/users/login', model, cbSuccess, cbError, cbAlways, (data)=> {
            localStorage.setItem("id_token", data.id_token);
            this.loggedInObservable.map((val) => console.log('HELLO?'));
        });
    }

    isLoggedInObservable() {
        return this.loggedInObservable;
    }
}

尽管观察者有一个值,地图功能什么也不会调用.

the map does NOTHING at all (the 'HELLO?' isn't being displayed), although the observer has a value the map function does not call anything.

使用观察者:

import {Component, OnInit, OnDestroy} from '@angular/core';
import {UserService} from '../../services/userservice';

@Component({
  selector: 'test-thing',
  template: require('./test-thing.html'),
  styles: [require('./test-thing.scss')],
  providers: [],
  directives: [],
  pipes: []
})
export class TestThing implements OnInit, OnDestroy{
    private isLoggedIn = false;
    private sub: any;

    constructor(private userService: UserService) {

    };

    ngOnInit() {
      this.sub = this.userService.isLoggedInObservable().subscribe(loggedIn => {
        this.isLoggedIn = loggedIn;
      });
    }

    ngOnDestroy() {
      this.sub.unsubscribe();
    }
}

初始值按预期工作,但是当我成功登录(使用地图)后尝试更改该值时,什么也没有发生,什么也没有.

The initial value is working as intended but when I try to change the value after a successful login (with map) nothing happens, nothing at all.

推荐答案

好吧,看来我需要的是 BehaviorSubject ,因为您可以将值推入其中,订阅它以获得更改并进行投影这是我第一次需要时获得的最后一个值.

Ok so seems what I needed is a BehaviorSubject since you can push values into it,subscribe to it to get changes and it projects the last value it got the first time you subscribe to it which is exactly what I need.

我的代码如下:
userservice.ts

My code is now as follows:
userservice.ts

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {serverPost} from '../../functions';
import {BehaviorSubject} from 'rxjs/BehaviorSubject'
import {tokenNotExpired} from 'angular2-jwt';

@Injectable()
export class UserService {
    private isLoggedInSubject: BehaviorSubject<boolean>;

    constructor(private http: Http) {
        this.isLoggedInSubject = new BehaviorSubject(this.checkIsLoggedIn());
    }

    get loggedInObservable() {
        return this.isLoggedInSubject.asObservable();
    }

    checkIsLoggedIn() {
        let isLoggedIn = false;
        try {
            isLoggedIn = tokenNotExpired();
        } catch(e) {

        }
        return isLoggedIn;
    }

    signUp(model, cbSuccess=null, cbError=null, cbAlways=null) {
        serverPost(this, '/api/users', model, cbSuccess, cbError, cbAlways, (data)=> {
            localStorage.setItem("id_token", data.id_token);
            this.isLoggedInSubject.next(this.checkIsLoggedIn());
        });
    }

    login(model, cbSuccess=null, cbError=null, cbAlways=null) {
        serverPost(this, '/api/users/login', model, cbSuccess, cbError, cbAlways, (data)=> {
            localStorage.setItem("id_token", data.id_token);
            this.isLoggedInSubject.next(this.checkIsLoggedIn());
        });
    }
}

这就是我在组件中使用它的方式:

And this is how I use it in a component:

export class TestComponent implements OnInit, OnDestroy{
    private isLoggedIn = false;
    private loginSub;

    constructor(private userService: UserService) {

    };

    ngOnInit() {
      this.loginSub = this.userService.loggedInObservable.subscribe(val => {
        this.isLoggedIn = val;
      });
    }

    ngOnDestroy() {
      this.loginSub.unsubscribe();
    }

}

此设置非常适合我的需求.

This setup works perfectly for my needs.

这篇关于如何重新加载/刷新angular2中的所有当前组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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