将数据从组件传递到服务,然后传递到另一个组件

时间:2017-08-02 12:22:14

标签: angular typescript observable angular-services angular-components

First Component.ts

onRecievingResults(value){
    console.log(value);
    this.faqService.saveData(value);
    console.log(value);
    this.router.navigate(['results'], {relativeTo: this.route});}
}

在此onRecievingResults()功能中,点击按钮,我将输入文本保存到saveData()服务中的方法faqService

Service.ts

saveData(value){
    console.log("save data function called " + value + this.sharingData.name);
    this.sharingData.name;
}
getData()
{
    console.log('get Data function called ');
    return this.sharingData.name;
}
getServers(name){
    return this.http.get(Staticdata.apiBaseUrl + "/2.2/search/advanced?key="+ Staticdata.key +"&access_token="+ Staticdata.access_token +"&/2.2/search/advanced?order=desc&sort=activity&accepted=True&closed=True&title=" + name + Staticdata.redirectUrl + "&filter="+ Staticdata.filters)
        .map(
        (response: Response) => {
            const items = response.json();
            return items;
        },
    )
    .catch(
        (error: Response) => {
            return Observable.throw(error);
        }
    );  
  }
}

在这项服务中,我有3个方法getData(),这里我从第一个组件中获取值并将其存储在另一个称为saveData()的方法中。 getServers()方法用于发出Http请求。

Second component.ts

export class SearchResultsComponent implements OnInit {

 data: any[];   
 item: any[];
 myName:any;

 constructor(private service: FaqService) {
  this.service =  service;
  console.log('back called');
  this.myName = service.getData();  
  console.log(this.myName);
 }

 ngOnInit() {
  this.service.getServers(this.myName)
        .subscribe(
        (data) => {
            this.item= data.items;
            console.log(this.item);
        },
        (error) => console.log(error)
    ); 
    }
  }

在此,我调用方法getData()来获取值并从Http请求中获取结果。

这里的问题是需要垃圾值并给出结果。如何从inputbox动态获取文本并将其存储在服务中并将其传递给其他组件。

1 个答案:

答案 0 :(得分:2)

您可以使用ObservableBehaviorSubject创建共享服务并使用myName方法更新next()变量,让第二个组件了解更改。

service.ts:

  sharingData = { name: " " };

  // Observable string source
  private dataStringSource = new BehaviorSubject<string>();

  // Observable string stream
  dataString$ = this.dataStringSource.asObservable();

  constructor(private http: Http) { }

  public saveData(value){
    console.log("save data function called " + value + this.sharingData.name);
    this.sharingData.name = value;
    this.dataStringSource.next(this.sharingData.name);
  }

first.component.ts:

  constructor(private router: Router, private faqService: FaqService){ }

  ngOnInit(){

  }

  onRecievingResults(value){
    console.log(value);
    this.faqService.saveData(value);
    this.router.navigate(['results']);
  }

second.component.ts:

item: any[];
myName:any;

  constructor(private router: Router, private service: FaqService){

    this.service.dataString$.subscribe(
      data => {
        if(this.myName !== data){
          this.myName = data;
          this.getServersData(this.myName);
        }
      });
  }

这是plunker demo