angular - 将数据从一个组件传递给服务,然后再传递给另一个组件

标签 angular typescript observable angular-services angular-components

第一个 Component.ts

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

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

服务.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 请求中获取结果。

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

最佳答案

您可以通过使用 Observable 创建共享服务来使第二个组件了解更改。和 BehaviorSubject和更新 myName变量使用 next()方法。

服务.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']);
  }

第二个.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

关于angular - 将数据从一个组件传递给服务,然后再传递给另一个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45460772/

相关文章:

angular - 类型 'Observable<unknown>' 不可分配给类型 'Observable<Lesson[]>'

Angular Service Worker 在子目录中不起作用

html - 如何在 Angular/Ionic 框架中设置 ionic 输入的样式?

Angular Platform-Server 响应自定义 http 状态码

javascript - 编译 TypeScript 时出现 Ionic 2 语法错误

button - 将 Polymer 按钮绑定(bind)到 Dart 代码

javascript - 错误类型错误 : Cannot set property 'paginator' of undefined

javascript - 如何在运行时在 nestjs 中扫描所有装饰器值

angular - 如何在 Angular 模板中显示值为 0 的 promise/observable?

Angular:数据仅在订阅方法中可用,但在外部不可用