[英]share data between two angular component
我是有角度的2.0初学者,想知道是否有人可以帮助我将数据从一个组件传递到另一个组件。
我的项目由三部分组成,一个登录窗口组件,一个表组件和一个用于处理路由的中心组件。 当用户登录登录组件时,http.post请求将发送到服务器进行身份验证。 如果凭据是真实的,则将从服务器返回包含用户信息的json。 该页面还将被路由到一个表组件,该表组件显示该用户的名称及其其他信息。
使用路由器出口,这两个组件位于同一页面上。
这是我的app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'td-app',
template: `
<router-outlet></router-outlet>
`
})
export class AppComponent {
}
app.module.ts:
@NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
JsonpModule,
RouterModule.forRoot([
{
path: 'login',
component: LoginComponent
},{
path: 'table',
component: TableComponent
},{
path: '',
redirectTo: '/login',
pathMatch: 'full'
}
])
],
这是我想传递给另一个组件的数据。 postUser方法正在执行http.post,并且将返回json字符串。 我想将此json数据传递给我的下一个组件。 我在考虑使用promise来确保将数据分配给变量userInfoPack ,然后将userInfoPack传递给下一个组件的模板。
login.component.ts:
postUser(body: User): Promise<any>{
return Promise.resolve( this.getUser(body))
.then(response => this.userInfoPack = response );
}
getUser(body: User){
this.userJson = JSON.stringify(body);
this.loginservice.postUser(this.userJson)
.subscribe(response => this.userInfo= response);
return this.userInfo; //subscribe method ends here
}
这是我想要传递数据的模板。 我想使用@input
传递数据,但我不知道如何。
table.component.ts:
template: `
<h2>Hi, {{userInfoPack}}</h2>
`
还有什么方法可以将页面路由到另一个组件,因为我使用按钮来路由页面并同时发送http.post请求以验证帐户。
<button type= "button" class="btn btn-primary btn-lg"
(click)= "postUser(user)" style=" position: relative;
left: 90%;" routerLink= '/whoison'>
Login
</button>
发送凭据并进行身份验证后,我不怎么路由组件。 (我们可以在函数而不是指令中使用routeLink吗?)
任何建议或意见都会有所帮助,谢谢!
最好的解决方案是创建一个共享服务来维护您的数据。 在我的一个Angular应用程序中,我也遇到了类似的挑战。 创建了sharedService指令/类,并将其注入/导入到两个控制器中。 现在由于服务的单例性质,一旦您从一个控制器更新了数据,便可以从另一控制器获取/读取数据。 Angular 2的一个很好的例子:
将您的共享服务引导到您的应用程序中:
bootstrap(AppComponent, [ SharedDataService ]);
不要在组件的provider属性中再次添加它。 这样,您将拥有整个应用程序的单个服务实例。
@Component({
selector : "selectorName",
// providers : [SharedDataService ], //---- not needed
template : `I'm MyComponent and shared data is: {{data}}`,
})
export class MyComponent implements OnInit{
(...)
}
我找到了一种简单的方法。
如果您只想共享字符串变量,我们可以使用本地存储 。
例如
app.component.ts
localStorage.set('name', 'yeehaah');
其他组件
var name = localStorage.get('name');
这样,您可以从“ app.component”访问“ other.component”中的名称变量“ yeehaah”
欢迎对此进行详细说明!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.