【问题标题】:how to use callback function in angular 4?如何在 Angular 4 中使用回调函数?
【发布时间】:2017-12-15 12:36:19
【问题描述】:

我曾经使用google api获取当前地址,现在我想使用angular 4在这个函数中实现回调函数如何实现它?

 let currgeocoder = new google.maps.Geocoder();
   currgeocoder.geocode({
      'location': location
   }, function(results:any, status:any) {
      if (status == google.maps.GeocoderStatus.OK) {
        let place = results[0];
       //this.showresult(place.formatted_address);
      } else {
          alert('Geocode was not successful for the following reason: ' + status);
      }
   });

      this.myGroup.setValue({
      searchControl: 'global'
    });

【问题讨论】:

  • 如果您需要任何事情,请查看我的回答

标签: angularjs angular function callback


【解决方案1】:

您可以创建 oberservable 并在其上推送新值,

let subject = new Subject(); 
let ovservable = subject.asObservable()

subject.next("b");

ovservable.subscribe((value) => {
  console.log("Subscription got", value); // Subscription wont get 
                                          // anything at this point
});

所以创建 observable 并将其公开,当您从调用中接收数据时,请使用 .next() 方法


在你的代码中

let subject = new Subject(); 
let ovservable = subject.asObservable();
let currgeocoder = new google.maps.Geocoder();
   currgeocoder.geocode({
      'location': location
   }, function(results:any, status:any) {
      if (status == google.maps.GeocoderStatus.OK) {
        let place = results[0];
        subject.next(place);
       //this.showresult(place.formatted_address);
      } else {
          alert('Geocode was not successful for the following reason: ' + status);
      }
   });

      this.myGroup.setValue({
      searchControl: 'global'
    });

    ovservable.subscribe((value) => {
      console.log("Subscription got", value); // Subscription wont get 
                                              // anything at this point
    });

【讨论】:

  • 我想在 showresult 函数中传递 results[0] 值,那该怎么做呢?
  • 什么是 asObservable()?我需要导入任何库吗?
  • 我在 cmd 中收到此错误:TS2304: 找不到名称“主题”。
  • @dgpoo - 请在你的 Angular 项目中导入 RXJs 库
  • @dgpoo - 你可以为这个 ovservable.subscribe((value) => { yourfunction()}) 调用你的功能;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
  • 2018-07-30
  • 1970-01-01
  • 1970-01-01
  • 2014-11-14
相关资源
最近更新 更多