如何在视图中显示响应数据?

时间:2017-03-17 10:07:02

标签: angular

我有这个登录组件:

import {Component, EventEmitter, Input, OnChanges} from '@angular/core';
import {Observable} from 'rxjs/Rx';
import { LoginService } from '../services/login.service';
import { Login } from '../model/login'
import {Router} from '@angular/router';
@Component({
    selector: 'login',
    templateUrl: 'login-form',

})
export class LoginComponent {
  data : any;
  // Constructor with injected service
      constructor(
          private loginService: LoginService,
          private router: Router
          ){}

      submitLogin(values){

             var current = this;
             // Variable to hold a reference of addComment/updateComment
             let loginOperation:Observable<any>;
             loginOperation = this.loginService.Login(values);
             loginOperation.subscribe(
               res => {
                 if(res.isLoggedIn == true){
                    current.router.navigate(['/home']);
                 }
                },
               err => { console.log(err) }

            );
           }


}

现在,如果用户已登录即时发送用户的响应数据并将其导航至/home。在路线我有这个:

  {path: 'home', component: LogsComponent}

这是我的LogsComponent:

import {Component, EventEmitter, Input, OnChanges} from '@angular/core';
import {Observable} from 'rxjs/Rx';
import {Router} from '@angular/router';
@Component({
    selector: 'dashboard',
    templateUrl: 'home',

})
export class LogsComponent {



}

所以我想要的是在响应中显示家庭视图数据,如下所示:

{{ response.user.email }}

有任何建议我该怎么做?

3 个答案:

答案 0 :(得分:2)

如果您希望在组件之间共享数据 ,您应该使用共享服务来满足此特定要求,您可以使用 router parameter ,在其他答案中显示。

1)创建服务。

<强> SharedService.ts

import {Component, Injectable} from '@angular2/core';

export class User{
 name:string,
 email:string
}

@Injectable()
export class SharedService{
  user:User;
  setUserDetail(res){
   this.user=res;
  }
  getUserDetail(){
    return this.user;
  }
}

2) 注入 SharedService 在应用程序的 appcomponent/rootcompnent 中。< / p>

<强> appModule.ts

import {SharedService} from './SharedService';

@NgModule({
  imports:[...],
  ...

  providers:[SharedService]                    //<<<===here
})

3)设置 user object 中定义的 SharedService

import {SharedService} from './SharedService';

export class LoginComponent {
  data : any;
  // Constructor with injected service
      constructor(
          private loginService: LoginService,
          private router: Router,
          private ss:SharedService            //<<<====added in constructor
          ){}

      submitLogin(values){

             var current = this;
             // Variable to hold a reference of addComment/updateComment
             let loginOperation:Observable<any>;
             loginOperation = this.loginService.Login(values);
             loginOperation.subscribe(
               res => {
                 if(res.isLoggedIn == true){
                    //current.router.navigate(['/home']);

                    this.ss.setUserDetail(res); //<<<===assuming res contains name and email.
                 }
                },
               err => { console.log(err) }

            );
           }
}

4) user object

LogsComponent
import {User} from './SharedService'            //<<<====added

@Component({
    selector: 'dashboard',
    templateUrl: 'home',

})
export class LogsComponent {

 user:User;                                    //<<<====added

 Constructor(ss:SharedService){                //<<<====added
       this.user=ss.getUserDetail();           //<<<====added
 }

}

5)在视图中,

{{user.email}}

注意: 这可能包含一些语法错误,因为这个答案是手工编写的,没有复制粘贴。

答案 1 :(得分:0)

什么是templateUrl?
templateUrl是这样的:templateUrl: './home.html' 对于你的问题,你是否将变量发送给LogsComponent? 你可以尝试:

import {Component, EventEmitter, Input, OnChanges} from '@angular/core';
import {Observable} from 'rxjs/Rx';
import { LoginService } from '../services/login.service';
import { Login } from '../model/login'
import {Router, ActivatedRoute} from '@angular/router';
@Component({
    selector: 'login',
    templateUrl: 'login-form',

})
export class LoginComponent {
  data : any;
  // Constructor with injected service
      constructor(
          private loginService: LoginService,
          private router: Router
          ){}

      submitLogin(values){

             var current = this;
             // Variable to hold a reference of addComment/updateComment
             let loginOperation:Observable<any>;
             loginOperation = this.loginService.Login(values);
             loginOperation.subscribe(
               res => {
                 if(res.isLoggedIn == true){
                    current.router.navigate(['/home'+ res.email]);
                 }
                },
               err => { console.log(err) }

            );
           }


}

在路线中我有这个:

  {path: 'home:id', component: LogsComponent}

这是我的LogsComponent:

import {Component, EventEmitter, Input, OnChanges} from '@angular/core';
import {Observable} from 'rxjs/Rx';
import {Router} from '@angular/router';
@Component({
    selector: 'dashboard',
    templateUrl: 'home.html',

})
export class LogsComponent {
  private resEmail: any;
  constructor(
    private route: ActivatedRoute,
    private router: Router
) {
}
  this.route.params
        .subscribe((params) => {
            this.resEmail = params['id'];
        });
}

你应该home.html

<span>{{resEmail}}</span>

答案 2 :(得分:0)

我对原始rxjs响应不太满意,因为我更喜欢处理promises,但我想res中的submitLogin()变量包含要显示的数据。在组件之间共享数据的常用方法是使用服务

LoginComponent

loginOperation.subscribe(
    res => {
        if(res.isLoggedIn == true){
            LoginService.setUserData(res);                 // store data in `LoginService`
            current.router.navigate(['/home']);
        }
    },
    err => { console.log(err) }
);

<强> login服务

@Injectable()
export class LoginService {
    ...
    userData: any;
    ...

    setUserData(data: any): void { this.userData = data; }
    getUserData(): any { return this.userData; }
}

LogsComponent

export class LogsComponent implements OnInit {
    response: any;

    constructor(private loginService: LoginService) {}

    ngOnInit() {
        this.response = this.loginService.getUserData();
    }
}

...现在,您的{{ response.user.email }}应该显示请求的数据。