在两个angularjs组件之间共享数据

时间:2016-12-01 16:47:32

标签: javascript angular http

我是angularjs 2.0初学者,并想知道是否有人可以帮助我将数据从一个组件传递到另一个组件。

我的项目由三部分组成,一个是登录窗口组件,一个表组件和一个处理路由的中心组件。当用户登录登录组件时,http.post请求将被发送到服务器进行身份验证。如果凭证是真实的,则json包含用户'信息将从服务器返回。该页面也将被路由到一个表组件,显示该用户的名称和他/她的其他信息。

这两个组件使用router-outlet在同一页面上。

这是我的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 而不是指令吗?)

任何建议或建议都会有所帮助,谢谢!

2 个答案:

答案 0 :(得分:1)

最佳解决方案是创建共享服务以维护您的数据。我在一个Angular应用程序中遇到了类似的挑战。创建一个sharingService指令/类并注入/导入到两个控制器中。现在由于服务的单例性质,一旦从一个控制器更新数据,就可以从其他控制器获取/读取数据。 Angular 2的一个很好的例子:

将您的共享服务引导到您的应用程序中:

bootstrap(AppComponent, [ SharedDataService ]);

不要在组件的providers属性中再次添加它。这样,您将拥有整个应用程序的单个服务实例。

@Component({
  selector : "selectorName",
  // providers : [SharedDataService ], //---- not needed
  template : `I'm MyComponent  and shared data is: {{data}}`,
})
export class MyComponent implements OnInit{
  (...)
}

答案 1 :(得分:0)

我发现了一种简单的方法。

如果您只想共享字符串变量,我们可以使用本地存储

e.g。

app.component.ts

localStorage.set('name', 'yeehaah');

other.component.ts

var name = localStorage.get('name');

这样,您就可以访问名称变量&#39; yeehaah&#39;在&#39; other.component&#39;来自&#39; app.component&#39;

欢迎详细说明!