angular2 - 在组件之间传递数据对象

2024-01-03

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

我有一个位于一个组件中的数据对象,该数据对象是从 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 = [];
}

}

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

所以,里面组成部分一, 你应该做:

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

和里面第二部分你应该添加:

@Input() user;

您将无法在组件二的承包商内访问此输入,只能在其“ngOnInit”内访问。看this https://stackoverflow.com/q/33561845/916450以供参考

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

angular2 - 在组件之间传递数据对象 的相关文章

随机推荐

  • 如何从不同文件夹中的另一个.py调用def

    我有以下结构 utils dir 有generator py 文件 其中有3 个def 我在 inline dir 中有 test py 我正在尝试在 test py 中使用生成器 py 中的 defs inline dir 和 utils
  • 方法产量如何运作?

    在javadoc中有说yield方法 导致当前正在执行的线程对象暂时暂停并允许其他线程执行 凯瑟琳 塞拉 Katherine Sierra 和伯特 贝茨 Bert Bates SCJP 书中说 Yield 应该做的是 使当前正在运行的线程头
  • 标准形式 matplotlib -- 将 e 更改为 \times 10

    在 matplotlib 中 轴有时以标准形式显示 数字由刻度显示 类似 1e 7 的内容由轴显示 有没有办法将其更改为写出的 times 10 7 我不想更改每个刻度上的标签 我希望更改出现在轴底部的 1e 7 文本 最简单的答案 使用乳
  • 如何验证或验证 JWT 签名?

    我正在尝试在 Java 中验证 JWT 令牌 如何验证或验证 JWT 令牌的 JWT 签名 您可以使用 Spring Security 中的 JWT 库 网址为https github com spring projects spring
  • Android 短信发送状态

    我需要在我的 Android 应用程序中实现一个功能来发送短信 我找到了许多与此相关的教程 但无法获得交付状态 失败或正常 以下是我的短信方法 private void sendSmsMessageWithStatus String pho
  • SWT Shell 根据子项调整大小

    我正在研究这个Composite画布上还有其他Composite可以添加和删除 我对整个布局概念的理解仍然很模糊 当孩子被添加到容器中时 考虑到容器有一个GridData它填充了父级 父级不应该也知道子级调整了大小吗 由于外壳 顶部父级 的
  • Google 可视化 API 示例中的“无效 JSON 字符串”

    我大致如下这个例子 http code google com apis chart interactive docs dev gviz api lib html tojsonexample 但一定是在做一些愚蠢的事情 服务器端Django视
  • C# winform 应用程序未获取 Machine.Config 中的 maxTimeout 值

    我一直在开发一个带有 Oracle 10g 数据库的 winform 应用程序 该应用程序正在使用TransactionScope并想修改maxTimeOut指定的值机器配置文件 我的机器配置文件位于以下位置 我为此应用程序使用 net 4
  • 改进 malloc() 算法的下一步是什么? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我自己写的简单malloc 函数 我想创建更快 更高效的变体 我编写的函数使用线性搜索并在内存中顺序连续分配 改进该算法的下一步是什么
  • 如何保存拟合的 R 模型以供以后使用

    很抱歉这个新手问题 如果我适合lm 型号或loess 模型 并将模型保存在文件或数据库中的某个位置 以供第三方以后使用predict 方法 我是否必须保存整个模型对象 由于返回的模型对象包含原始的原始数据 因此返回的对象可能会很大 如果您包
  • 使用 POI 在 Excel 中设置时间

    我正在尝试使用 Java 中的 POI api 创建 Excel 工作表 在该 Excel 工作表中 我想要一个仅包含 TIME 的单元格 通过设置此值 我们可以将单元格包含在该特定列的求和中 就像我们在数字列中所做的那样 为此 我们需要将
  • Java/XSD 解析

    我怀疑是否有这样的事情 但我想问一下 有谁知道Java中是否有一个库可以读取xsd文件并 创建 定义的元素 例如以字符串格式在代码中使用 例如 阅读以下架构
  • 是什么让 Mersenne Twister Tempering 功能可逆?

    众所周知 MT回火功能是可以逆转的 可以在线获取源代码来执行此操作here http b10l com p 24 我试图弄清楚这是如何工作的 以及如何以编程方式解决这个问题和类似的问题 我正在努力解决的是 对有限大小的变量进行移位操作会导致
  • 计算 pandas 数据框中连续正值的有效方法

    我试图计算 pandas 数据框中每列的连续积极事件的数量 这里DSM提供的解决方案 计算Python数组中的连续正值 https stackoverflow com questions 27626542 counting consecut
  • 名为 X 的 EntityManager 没有持久性提供程序

    我正在使用 JPA 开发 JavaSE 应用程序 不幸的是 我得到null致电后 Persistence createEntityManagerFactory PERSISTENCE UNIT NAME 下面你会发现 我的代码片段调用Ent
  • 平移动画后按钮未响应单击事件

    我已经在按钮上执行了翻译动画 一切都按我的预期工作 但唯一的问题是动画之后按钮没有响应单击事件 请纠正我 Button b Button findViewById R id button1 TranslateAnimation slide
  • 像这样使用 EF 将多个查询聚合为一个查询吗?

    我在我的应用程序中使用 EF 4 0 POCO 像这样检索信息有什么缺点吗 Given a customerId and a productId 我想应用一些业务规则 要求我从需要多次查询的数据库中获取大量微小的信息 相反 我可以编写一个查
  • 从 main “返回”的正确方法

    假设我们有这样的程序 int main int argc char argv if argc lt 3 printf usage details n return EXIT FAILURE dostuff return EXIT SUCCE
  • 如何仅从 DateTime 获取小时和分钟

    我可以说 2015 01 16 13 50 00 000 在我的数据库中 如何仅获取小时和分钟 13 50 最后我想像这样进行查询 更新 A 设置状态 1 WHERE endTime current time endTime 我上面示例的字
  • angular2 - 在组件之间传递数据对象

    如果可能的话 寻求一些帮助 我有一个位于一个组件中的数据对象 该数据对象是从 REST 调用接收到的 它包含我想跨组件共享的用户详细信息 但我遇到了麻烦 将此对象传递给另一个组件以便我可以使用详细信息的最佳方法是什么 前任 数据对象名为 u