Angular2检测父项中的集中数据变量

时间:2015-11-27 00:17:27

标签: typescript angular

这是关于如何处理这个小模式的另一个快速。我想更新我的父组件中的一个变量,该变量已从集中服务中分配了一个值,该服务将保存我的数据,以便我可以在整个应用程序中共享它。我正在使用 typescript Angular2.alpha46 构建。

采取以下措施:)

Main.ts:

import {Component, CORE_DIRECTIVES, Observable, Input, bootstrap} from 'angular2/angular2';
import {RouteConfig, RouterLink, ROUTER_DIRECTIVES} from 'angular2/router';
import {Routes,  APP_ROUTES} from './core/route.config';
import {UserService} from "./shared/service/user.service";
import {InMenu} from './shared/pipe/inmenu.pipe';

@Component({
    selector: 'Main',
    providers: [],
    templateUrl: './app/main.html',
    directives: [ROUTER_DIRECTIVES, CORE_DIRECTIVES, RouterLink],
    pipes: [InMenu]
})

@RouteConfig(APP_ROUTES)

export class Main {
    routes = APP_ROUTES;
    loggedIn: Boolean;

    constructor(private UserService: UserService) {
        this.loggedIn = UserService.isLoggedIn();
    }
}

main.html(我的loggedIn变量绑定的一部分)

<header>
    <span>LOGGED IN STATUS: {{loggedIn}}</span>
</header>

user.service.ts(简化)

import {Inject} from 'angular2/angular2';
import {Http, HTTP_BINDINGS, Headers} from 'angular2/http';
import {ROUTER_BINDINGS} from 'angular2/router';
import {User} from '../../model/user.model';

export class UserService {

    private user: User;
    private loggedIn: Boolean;

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

    getLoggedInUser() {
        return this.user;
    }

    isLoggedIn() {
        return this.loggedIn;
    }

    login(user: User) {
        var postData = "email=" + user.email + "&password=" + user.password;

        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/x-www-form-urlencoded');

        return this.http.post('/auth/local', postData, {
                headers: this.headers
            })
            .map((res:any) => {
               // Update variable!!!!
               this.loggedIn = true;

               return this.handleResponse(res);
            });
     }

}

因此,从子组件我将调用userService方法登录,将loginIn布尔值更改为true。

子组件(我称之为服务方法)

import {Component, CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/angular2';
import {UserService} from '../../shared/service/user.service';
import {Router} from 'angular2/router';
import {User} from '../../model/user.model';
import {APP_ROUTES, Routes} from '../../core/route.config';

@Component({
    selector: 'login-form',
    templateUrl: 'app/login/components/login-form.component.html',
    directives: [CORE_DIRECTIVES, FORM_DIRECTIVES]
})

export class LoginFormComponent{
    user: User;
    submitted: Boolean = false;
    errorMessage = null;

    constructor(private userService:UserService, private router: Router) {
        this.user = new User();
    }

    onLogin() {
        this.submitted = true;

        this.userService.login(this.user)
            .subscribe(
                data => {},
                err => {}
            );
    }
}

我希望父视图能够相应地更新,但事实并非如此(显然)

什么是基本上强制消化的最佳解决方案&#34; (如角度1)重新渲染和更新父视图或检测从子组件更改的集中共享变量? EventEmitters?

再次感谢!

1 个答案:

答案 0 :(得分:3)

我会在UserService中为loggedIn添加一个Observer,并使组件订阅对该组的更改。

export class UserService {
    this.loggedIn$ = new Observable(observer => {
        this._loggedInObserver = observer;
    }).share();

    login(user: User) {
    var postData = "email=" + user.email + "&password=" + user.password;

    this.headers = new Headers();
    this.headers.append('Content-Type', 'application/x-www-form-urlencoded');

    return this.http.post('/auth/local', postData, {
            headers: this.headers
        })
        .map((res:any) => {
           this._loggedInObserver.next(true);

           return this.handleResponse(res);
        });
    }
}

然后在你的组件中只订阅新的观察者:

userService.loggedIn$.subscribe(loggedIn => {
   // Update local value
});