2017-01-23 21 views
9

Tôi đang cố gắng để đánh giá Angular 2 và tôi đang gặp vấn đề với các quan sát.Làm thế nào để tạo ra một quan sát trong Angular 2

Tôi đang cố gắng tạo một dịch vụ đơn giản mà ban đầu trả về một mảng được mã hóa cứng nhưng cuối cùng sẽ nhận được dữ liệu từ một dịch vụ web.

Tuy nhiên, tôi không thể xây dựng OK.

Bất kỳ ý tưởng nào?

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; 
    } 
    } 
} 
+0

https://angular.io/docs/ts/latest/guide/server-communication.html –

+0

Theo dõi "https://scotch.io/tutorials/angular-2-http-requests-with-observables". – moks

Trả lời

0

Đối với điều này, bạn có thể sử dụng 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'); 
    } 
} 

Một trong những biến thể của Đối tượng là BehaviorSubject, trong đó có một khái niệm "giá trị hiện tại". Nó lưu trữ giá trị mới nhất được phát ra cho người tiêu dùng của nó và bất cứ khi nào một Observer mới đăng ký, nó sẽ ngay lập tức nhận được "giá trị hiện tại" từ BehaviorSubject. Đối tượng hành vi luôn trả về dữ liệu cuối cùng. Để biết thêm info

26

Bạn có thể sử dụng phương thức Observable.of.

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

Đừng quên nhập của việc sử dụng các dòng sau

import "rxjs/add/observable/of"; 
+2

Điều này thực sự tiện dụng. Tôi đã tạo một ví dụ để tôi tham khảo. http://jsbin.com/kebofob/1/edit?js,console,output – Rich

+0

Điều này thực sự phải là câu trả lời được chấp nhận. Cảm ơn bạn! – perry

+2

Tôi đã phải sử dụng 'nhập khẩu 'rxjs/thêm/quan sát/của"; 'với Angular 5.0.3 –

12

này đang đến hơi muộn, chỉ cần làm rõ anyways. Đây là cách bạn có thể tạo ra một quan sát đơn giản trong trường hợp bạn muốn bắt chước lời hứa của riêng bạn. Bạn làm

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); 

    }) 

để đăng ký nó là rất dễ dàng

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

bạn cũng có thể chuyển nó sang hứa sử dụng toPromise() or fromPromise(observable) điều hành và vân vân.

+1

Điều này thực sự gây ra vấn đề cho tôi. Tôi có một dịch vụ trả về một loại có thể quan sát được. Lần đầu tiên nó sẽ trả về một Observable được trả lại từ một bài đăng http, bất kỳ lúc nào sau đó nó sẽ trả về dữ liệu được lưu trữ, phương thức này không hoạt động vì Observable.create (dữ liệu) không hoàn toàn giống nhau. Observable.of (dữ liệu) là cách tốt nhất. –

+0

Trong Angular bạn sẽ không nhận được bất kỳ tự động hoàn thành hoặc đánh máy khi sử dụng Observable.create() - Tôi đã cố gắng nhưng phải hoàn nguyên về 'new Observable' – Ryan

Các vấn đề liên quan