javascript - Angular 4 单例服务

标签 javascript angular

我正在尝试创建一个服务来在两个组件之间共享数据。我将服务注入(inject)到根模块中,通过对根模块提供程序进行 DI 来使其在整个应用程序中都可以访问。我的代码大致如下所示。

服务

    @Injectable(){
    export class ForumService{
       forum: any;

       setForum(object){
          this.forum = object; 
       }

       getForum(){
          return this.forum;
       }
    }

根模块

.......
import { ForumService } from 'forumservice';
.......

@NgModule({
  declarations: [.....],
  imports: [.....],
  providers: [....., ForumService],
  bootstrap: [AppComponent]
})
export class AppModule{}

组件一

//A bunch of import statements

import { ForumService } from 'forumservice'; //Without this Angular throws a compilation error

@Component({
  selector: 'app-general-discussion',
  templateUrl: './general-discussion.component.html',
  styleUrls: ['./general-discussion.component.css'],
  providers: [GeneralDiscussionService]     //Not injecting ForumService again
})

export class GeneralDiscussionComponent implements OnInit{

  constructor(private forumService: ForumService){}

  ngOnInit(){
     helperFunction();
  }

  helperFunction(){
     //Get data from backend and set it to the ForumService
     this.forumService.forum = data;
     console.log(this.forumService.forum); //prints the data, not undefined
  }
}

组件二

//A bunch of import statements

import { ForumService } from 'forumservice'; //Without this Angular throws a compilation error

@Component({
   selector: 'app-forum',
   templateUrl: './forum.component.html',
   styleUrls: ['./forum.component.css'],
   providers: []
})

export class ForumComponent implements OnInit {
   forumData: any;

   constructor(private forumService: ForumService){}

   ngOnInit(){
      this.forumData = this.forumService.forum;  // returns undefined         
   }
}

一旦我从组件一导航到组件二,我就会期待“这是一个字符串”。但是我得到了 undefined。是因为组件中的 import 语句吗?如果我删除它,我会看到一个编译错误,提示未找到 ForumService

最佳答案

不要使用 getter 和 setter,而是直接在组件中使用对象(不是 primitibe,例如字符串)。

您的服务

@Injectable(){
export class ForumService{
   forum:any = {name:string};
}

组件一

export class GeneralDiscussionComponent implements OnInit{

  constructor(private forumService: ForumService){}

  ngOnInit(){
    this.forumService.forum.name="This is a string";
  }
}

成分二

export class ForumComponent implements OnInit {
// forumTitle: string; // do not need this anymore
   forum:any; // use the forum.name property in your html

   constructor(private forumService: ForumService){}

   ngOnInit(){
      this.forum = this.forumService.forum;  // use the          
   }
}

我知道封​​装更可取,而您当前的代码可能会遇到一些时序问题。但是在服务中使用共享数据时,您可以像上面那样双向绑定(bind)变量,并且您的组件将保持同步。

编辑:

还有一个重要的注意事项,你想要在组件之间同步的变量需要是一个对象。将 forumTitle:string 改为 forumTitle:any = {subject:string} 或类似内容。

否则,当您的服务中的数据发生变化时,您需要让您的组件成为数据的监听器。

关于javascript - Angular 4 单例服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45790386/

相关文章:

javascript - Angularjs 删除动态生成的行

javascript - 谷歌地图 : render map based on street address

javascript - 如何用js设置input元素值时触发change事件

angular - 如何在 Google App Engine 上部署 Angular 多语言应用程序

angular - ngx-datatable rowClass 不工作

Angular 6 - 单击或焦点时调用函数

angular - 如何在 Angular 6 单元测试中依赖注入(inject)接口(interface)

javascript - D3.js 对象之间的动态连接器

javascript - 如何在angular2中正确使用http服务?

JavaScript AJAX 库通过 JSONP 使用 WS REST