【问题标题】:How to create an observable in Angular 2如何在 Angular 2 中创建可观察对象
【发布时间】:2017-06-07 22:52:47
【问题描述】:

我正在尝试评估 Angular 2,但我遇到了 observables 的问题。

我正在尝试创建一个简单的服务,该服务最初返回一个硬编码数组,但最终会从 Web 服务中获取数据。

但是,我无法让它构建正常。

有什么想法吗?

export class FleetListService {

  private data: Observable<Array<IFleet>>;

  constructor() { }

  fleets: IFleet[] = JSON.parse( `[{ "id": 1, "name": "John", "description": "John has been in the Audio/Video industry since 1990. He has led DevAv as its CEO since 2003. When not working hard as the CEO, John loves to golf and bowl. He once bowled a perfect game of 300.", "childCount": 5, "isUsed": true }, 
                                   { "id": 2, "name": "Olivia", "description": "Olivia loves to sell. She has been selling DevAV products since 2012. Olivia was homecoming queen in high school. She is expecting her first child in 6 months. Good Luck Olivia.", "childCount": 5 }, 
                                   { "id": 3, "name": "Robert", "description": "Robert was recently voted the CMO of the year by CMO Magazine. He is a proud member of the DevAV Management Team. Robert is a championship BBQ chef, so when you get the chance ask him for his secret recipe.", "childCount": 4 }, 
                                   { "id": 4, "name": "Greta", "description": "Greta has been DevAV's HR Manager since 2003. She joined DevAV from Sonee Corp.  Greta is currently training for the NYC marathon. Her best marathon time is 4 hours. Go Greta.", "childCount": 11 }, 
                                   { "id": 5, "name": "Brett", "description": "Brett came to DevAv from Microsoft and has led our IT department since 2012.  When he is not working hard for DevAV, he coaches Little League (he was a high school pitcher).", "childCount": 13 }, 
                                   { "id": 6, "name": "Sandra", "description": "Sandra is a CPA and has been our controller since 2008. She loves to interact with staff so if you've not met her, be certain to say hi.  Sandra has 2 daughters both of whom are accomplished gymnasts.", "childCount": 44 }, 
                                   { "id": 7, "name": "Kevin", "description": "Kevin is our hard-working shipping manager and has been helping that department work like clockwork for 18 months.  When not in the office, he is usually on the basketball court playing pick-up games.", "childCount": 5 }, 
                                   { "id": 8, "name": "Cynthia", "description": "Cindy joined us in 2008 and has been in the HR department for 2 years.   She was recently awarded employee of the month. Way to go Cindy!", "childCount": 4 }, 
                                   { "id": 9, "name": "Kent", "description": "As our ombudsman, Kent is on the front-lines solving customer problems and helping our partners address issues out in the field.    He is a classically trained musician and is a member of the Chamber Orchestra.", "childCount": 26 }, 
                                   { "id": 10, "name": "Taylor", "description": "If you are like the rest of us at DevAV, then you've probably reached out for help from Taylor. He does a great job as a member of our IT department.", "childCount": 5 }, 
                                   { "id": 11, "name": "Sam", "description": "Sammy is proud to be a member of the DevAV team. He joined the team in 2012 and has been in the sales department from the beginning.  He has just picked up golf so you can find him on the links every weekend.", "childCount": 11 }, 
                                   { "id": 12, "name": "Kelly", "description": "Kelly loves people and that's why she joined DevAV's support department. One of the funniest people in the company, she does stand-up on the weekends at the Laugh Factory.", "childCount": 5 }, 
                                   { "id": 13, "name": "Natalie", "description": "Natalie travels the US and teaches our partners how to explain the benefits of our products to customers.  She is a proud wife and mom and volunteers her time at the elementary school.", "childCount": 29 }, 
                                   { "id": 14, "name": "Walter", "description": "Walter has been developing apps and websites for DevAV since 2011. His passion is software and if you ever walk by his desk, you'll know why.  Wally once worked 72 hours straight - writing code and fixing bugs.", "childCount": 13 }]`);

  getFleets(): Observable<IFleet[]> {
    return new Observable((data : IFleet[]) => {
      return this.fleets;
    }
  }
}

【问题讨论】:

标签: angular observable


【解决方案1】:

你可以使用 Observable.of 方法。

getFleets(): Observable<IFleet[]> {
     return Observable.of(this.fleet)
}

不要忘记使用以下行导入

   import "rxjs/add/observable/of";  // For RxJs  5.0+

对于 RxJS 6.x

getFleets(): Observable<IFleet[]> {
         return of(this.fleet)
    }

“of”的导入语句

import { of } from "rxjs";

【讨论】:

  • 这真的很方便。我创建了一个示例供自己参考。 jsbin.com/kebofob/1/edit?js,console,output
  • 这确实应该是公认的答案。谢谢老哥!
  • 我不得不在 Angular 5.0.3 中使用 import "rxjs/add/observable/of";
  • 我相信一旦硬编码数组的所有元素都被“处理”过,这将停止观察?根据问题,OP 希望继续观察,因为数据最终将通过网络服务更新。有没有办法做到这一点?
【解决方案2】:

这有点晚了,无论如何只是为了澄清。如果您想模仿自己的类似承诺,这就是您如何创建一个简单的可观察对象的方法。你会的

let observable=Observable.create(observer => {
      setTimeout(() => {
        observer.next("data to send can be object or anything");
        console.log("am done");
        observer.complete(); // to show we are done with our processing
       // observer.error(new Error("error message"));
      }, 2000);

    })

订阅很简单

observable.subscribe((data) => {
console.log(data); // should be 'data to send can be object or anything'
});

您也可以使用toPromise() or fromPromise(observable) 运算符等将其转换为promise。

【讨论】:

  • 这实际上给我带来了问题。我有一个返回一个类型的 Observable 的服务。第一次它会返回一个从 http post 返回的 Observable,之后它会返回缓存的数据,这个方法不起作用,因为 Observable.create(data) 并不完全相同。 Observable.of(data) 是最好的方法。
  • 在 Angular 中,您在使用 Observable.create() 时不会得到任何自动完成或打字 - 我正在尝试,但必须恢复到 new Observable
  • 如何取消订阅?
【解决方案3】:

为此,您可以使用 BehaviorSubject

export class FleetListService {
    public data: any = new BehaviorSubject('your hard coded data goes here');
    getdata() {
        //do your stuff
        this.FleetListService.next('new data got from server');
    }
}

Subject 的变体之一是 BehaviorSubject,它具有“当前值”的概念。它存储发送给其消费者的最新值,并且每当有新的观察者订阅时,它将立即从 BehaviorSubject 接收“当前值”。 行为主体总是返回最后一个数据。更多info

【讨论】:

  • 做得很好。谢谢
猜你喜欢
  • 1970-01-01
  • 2016-10-06
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
  • 1970-01-01
  • 2019-02-18
  • 2023-03-29
相关资源
最近更新 更多