【问题标题】:angular2 - passing data object between componentsangular2 - 在组件之间传递数据对象
【发布时间】:2016-07-22 11:19:33
【问题描述】:

如果可能的话,寻求帮助。

我有一个位于一个组件中的数据对象,从 REST 调用接收。它包含我想跨组件共享的用户详细信息,但我遇到了问题。

将此对象传递给另一个组件的最佳方法是什么,以便我可以使用详细信息?

例如。数据对象名为 user,我想与单独的组件共享从数据库创建并从 REST 调用接收到的 user._id。

感谢大家的帮助。

组件一(包含用户数据对象):

import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES, Router, Location} from 'angular2/router';
import {Control, FORM_DIRECTIVES, NgIf} from 'angular2/common';
import {UserLogin} from './navbar.login.service';
import {LoginService} from './navbar.login.service';
import {AccountDataService} from '../account/account.data.service';
import {User} from '../account/account.model';

@Component({
selector: 'navbar',
templateUrl: './app/navbar/navbar.component.html',
directives: [ROUTER_DIRECTIVES],
providers: [LoginService, AccountDataService]
})

export class NavbarComponent {

model: UserLogin;
user: User;
message: string;

constructor(private _service: LoginService, public _userService: AccountDataService,
    private router: Router, private location: Location) {
    this.model = this._service.modelInstance();
    this.user = this._userService.modelInstance();
}

onSubmit() {

    this._service.rawPost('?username=' + this.model.userName
        + '&password=' + this.model.password)
        .subscribe(res => {
            if (res.status === 200) {
                this.message = 'You have been logged in with: ' + this.model.userName;
                this.router.navigate(['Dashboard']);
                this._userService.read('/username/' + this.model.userName)
                    .subscribe(user => {
                        this.user = user; // <--- NEED THIS OBJECT PASSED AND SHARED!!
                })
                    });
            } else {
                this.message = 'Username or Password is not correct';
            }
        },
        error => {
            console.log("Response = %s", JSON.stringify(error));
            if (error.status == 401) {
                this.message = 'Username or Password is not correct';
            }
        });

}

toggleMenu() {
    this.menuActive = !this.menuActive;
}

logout() { //NOT SURE ABOUT THIS!!!
    // clears browser history so a user can't navigate with back button
    // this.location.replaceState('/');
    this.router.navigate(['Home']);
}

组件二需要调整。无法让上面的用户对象传入。此时甚至不确定从哪里开始。

import {Component, OnInit} from 'angular2/core';
import {UserCase} from './case/case.model';
import {User} from '../account/account.model';
import {ROUTER_DIRECTIVES} from 'angular2/router'; 
import {AccountDataService} from '../account/account.data.service';
import {NavbarComponent} from '../navbar/navbar.component';

@Component({
selector: 'dashboard',
templateUrl: './app/dashboard/dashboard.component.html',
directives: [NavbarComponent],
providers: [ROUTER_DIRECTIVES, AccountDataService],
})

export class DashboardComponent implements OnInit {

public user: User;
public userCase;
public userCases: UserCase[] = []

ngOnInit() {
    // Also trying to get each userCase object into the userCases array (not currently working)

    this._caseService.read('/user/' + this.user._id) //this.user not currently defined.
        .subscribe(userCase => {
            this.userCase = userCase;
        });

    this.userCases.push(this.userCase);
}

constructor(private _caseService: CaseDataService, private _userService: AccountDataService) {
    this.user = this._userService.modelInstance();
    this.userCase = this._caseService.modelInstance();
    this.userCases = [];
}

}

【问题讨论】:

    标签: angular angular2-directives angular2-services


    【解决方案1】:

    最好的方法是将数据作为“组件二”的输入传递。

    所以,在组件一中,你应该这样做:

    <dashboard [user]="user"></dashboard>
    

    组件二中你应该添加:

    @Input() user;
    

    您将无法在组件二的承包商内访问此输入,只能在其“ngOnInit”内访问。参考this

    【讨论】:

    • 应该是@Input() 用户;
    • 非常感谢!!这帮助很大。
    • 酷,如果回答了你的问题,请用“V”标记我的答案(:
    • 这绝对有帮助,您发送的参考链接也提供了很多见解。不过,您的解决方案有助于澄清它。
    • 如果我将子组件 ngOnInit 中的值称为未定义的 `ngOnInit() { console.log(this.user) }`
    猜你喜欢
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 2017-08-23
    • 2021-07-20
    • 2017-04-26
    相关资源
    最近更新 更多