【问题标题】:Passing data from a component to service and then to another component将数据从组件传递到服务,然后再传递到另一个组件
【发布时间】:2018-01-09 16:12:25
【问题描述】:

First Component.ts

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

在这个onRecievingResults() 函数中,单击按钮时,我将输入文本保存到称为faqService 的服务中的方法saveData()

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请求。

第二个组件.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请求中获取结果。

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

【问题讨论】:

  • 看看这个answer是否有帮助:)
  • 我如何告诉第二个组件数据已更新并为此提供结果。在这里它采用未定义的值并给出结果。 @Nehal
  • 你需要使用ObservableSubject。这是来自文档的exampleplunker
  • 您能否为上面发布的代码证明这一点。会有很大帮助。 @Nehal

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


【解决方案1】:

您可以通过使用ObservableBehaviorSubject 创建共享服务并使用next() 方法更新myName 变量来使第二个组件知道更改。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 2018-02-22
    • 1970-01-01
    相关资源
    最近更新 更多