Advertisement
Guest User

Untitled

a guest
Jul 26th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. // Some Factory in Angular 1
  2. var somethings = [];
  3. var service = {
  4. all: all
  5. };
  6. return service;
  7.  
  8. function all() {
  9. return $http
  10. .get('api/somethings')
  11. .then(function(response) {
  12. somethings = parseSomethings(response.data);
  13. return somethings;
  14. });
  15. }
  16.  
  17. // Some Controller in Angular 1
  18. var vm = this;
  19. vm.somethings = [];
  20. vm.loading = true;
  21.  
  22. loadThings();
  23.  
  24. function loadThings() {
  25. SomeFactory
  26. .all()
  27. .then(function(somethings) {
  28. vm.somethings = somethings;
  29. })
  30. .finally(function() {
  31. vm.loading = false;
  32. })
  33. }
  34.  
  35. // Some Service in Angular 2
  36. export class SomeService {
  37. private _somethings$: Subject<Something[]>;
  38. private dataStore: {
  39. somethings: Something[]
  40. };
  41.  
  42. constructor(private http: Http) {}
  43.  
  44. get _somethings$() : Observable<Something[]> {
  45. return this._somethings$.asObservable();
  46. }
  47.  
  48. loadAll() {
  49. this.http
  50. .get(`api/somethings`)
  51. .map(response => response.json())
  52. .subscribe(
  53. response => {
  54. this.dataStore.somethings = parseSomethings(response.data);
  55. this._somethings$.next(this.dataStore.somethings);
  56. }
  57. );
  58. }
  59. }
  60.  
  61. //Some Component in Angular 2
  62. export class SomeComponent() {
  63.  
  64. constructor(private someService: SomeService) {}
  65.  
  66. ngOnInit() {
  67. this.someService.loadAll();
  68. this.somethings = this.someService.somethings$;
  69. }
  70. }
  71.  
  72. create(something: Something) : Observable<Something>{
  73. return this.http.post(`api/somethings`, JSON.stringify(something))
  74. .map(response => response.json())
  75. .do(
  76. something => {
  77. this.dataStore.somethings.push(something);
  78. this._somethings$.next(this.dataStore.somethings); //Notify the subscribers
  79. }
  80. );
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement