嗨,我在angular 2中尝试过通过服务在组件之间进行通信,但是返回函数返回空值



我需要从第一个组件获取值的页面的第二个组件

    import { Component } from '@angular/core';
    import {AppService} from './app.service';
    import { Http,Response } from '@angular/http';    
@Component({
 template:
 `
        <h1>second component</h1>
        <h1>second component</h1>
        <p>{{myName}}</p>
 `,
 providers:[AppService]
            })
export class SecondComponent {      
    constructor(private appservice: AppService)
                    {
                        this.appservice=appservice;
                        this.myName=this.appservice.getDat();
                        console.log(this.myName);       
                    }    
                            }

**这是我需要将值传递给第二个组件的第一个组件页面**

import { Component } from '@angular/core';
import { FormBuilder, FormControl } from '@angular/forms'; 
import {AppService} from '../second/app.service';
import { Router }   from '@angular/router';
import { Http,Response } from '@angular/http';
import { routing, appRoutingProviders } from '../app.route';
import { Validators } from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
@Component({
  selector: 'first-app',
  templateUrl:"../app/src/component/first/app.firstpage.html",
  providers:[AppService]              
          })
export class FirstComponent 
{      
    data:any;      
    public edited=false;
    public city=false;
    public dateCon=false;
    inputForm: FormGroup;
    Select: FormControl;
    Selectt: FormControl;
    dat:FormControl;
  constructor(private appservice:AppService,builder: FormBuilder, router:Router)     
  {
              this.appservice.getData().subscribe(res=>{this.data=res.json()});
              console.log(this.data);
              this.Select = new FormControl('', [
                Validators.required
                                                  ]);
              this.Selectt = new FormControl('', [
                Validators.required
                                                ]);
              this.dat = new FormControl('', [
                Validators.required
                                                  ]);
              this.inputForm = builder.group({
              Select: this.Select,
              Selectt: this.Selectt,
              dat: this.dat
                                            });
              this.router=router;
              this.appservice=appservice;    
          } 
   ngOnInit(){
           this.appservice.getData()
             }
     onclick(a,b) {
          console.log(this.data);
          let sel1=this.inputForm.value.Select;
          let sel2=this.inputForm.value.Selectt;
          let sel3=this.inputForm.value.dat;
          console.log(sel3);
          console.log(sel1);
          console.log(sel2);
          console.log(this.data.bus.length);
            for(let i=0;i<this.data.bus.length;i++){
                  if((this.data.bus[i].from==sel1)&&(this.data.bus[i].to==sel2))
                                            {
      /*this.appservice.setData(this.data.bus[i]);*/     
                      this.appservice.setData(i);
                      console.log(i);
                                            }
                                                    }
                  if((sel1!="")&&(sel2!="")&&(sel3!="")&&(sel1!=sel2))
                  {
                          this.router.navigate(['/sec-component']);
                  }
                  else if((sel1=="")&&(sel2=="")&&(sel3==""))
                    {
                          this.edited=true;
                    }
                  if((sel1==sel2)&&((sel1!="")&&(sel2!="")))
                    {
                            this.edited=false;
                            this.city=true;
                    }
                  else 
                   {
                          this.city=false;
                     }
                  if(sel1!=sel2)
                     {
                          this.edited=false;
                     }
                  if(sel3=="")
                       {
                            this.dateCon=true;
                       }
                  else  
                   {        
                            this.dateCon=false;
                       }
 }       
}

服务。

import {Component, Injectable,Input,Output,EventEmitter} from '@angular/core'
import { Http, Response } from '@angular/http';
export interface myData 
{
   name:number;
}
@Injectable()
export class AppService 
{   
        sharingData: myData={name};
                setData(i)
                         {
                             console.log('save data function called' + i + this.sharingData.name);
                             this.sharingData.name=i; 
                             console.log(this.sharingData.name);
                         }
                getDat()
                        {
                            console.log(this.sharingData.name);
                            return this.sharingData.name;
                        }
        constructor(private http:Http){}
                 getData()
                        {
                            return this.http.get('./app/src/component/busDet.json')
                        }    
}

module.ts

import { NgModule }       from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { HttpModule }    from '@angular/http';
import {AppService} from './second/app.service';
import { ReactiveFormsModule } from '@angular/forms'; 
import { FormsModule }    from '@angular/forms';
import { routing, appRoutingProviders } from './app.route';
import { AppComponent }    from './app.component';
import { FirstComponent }  from './first/first.component';
import { SecondComponent }  from './second/second.component';
import { ThirdComponent }  from './third/third.component';
import { JsonpModule } from '@angular/http';
@NgModule({
  imports: [
    BrowserModule,
    FormsModule,ReactiveFormsModule,HttpModule,JsonpModule,
    routing
  ],
  declarations: [
    AppComponent,
    FirstComponent,
    SecondComponent,
    ThirdComponent 
  ],
  providers: [
    appRoutingProviders, AppService
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {
}

在应用模块(组件的通用模块)中注册你的服务,并从组件中删除注册。

尝试从第一个组件中删除providers:[appservice]。它开始工作得很好。(它实际上是再次注入服务,使sharingData变为null)

最新更新