2016-02-05 17 views
44

Tôi gặp một dịch vụ mà có phương pháp này:Làm thế nào để tạo ra một Observable từ dữ liệu tĩnh tương tự như http một trong Angular?

export class TestModelService { 

    public testModel: TestModel; 

    constructor(@Inject(Http) public http: Http) { 
    } 

    public fetchModel(uuid: string = undefined): Observable<string> { 
     if(!uuid) { 
      //return Observable of JSON.stringify(new TestModel()); 
     } 
     else { 
      return this.http.get("http://localhost:8080/myapp/api/model/" + uuid) 
       .map(res => res.text()); 
     } 
    } 
} 

trong constructor của thành phần Tôi đăng ký như thế này:

export class MyComponent { 
    testModel: TestModel; 
    testModelService: TestModelService; 

    constructor(@Inject(TestModelService) testModelService) { 
     this.testModelService = testModelService; 

     testService.fetchModel("29f4fddc-155a-4f26-9db6-5a431ecd5d44").subscribe(
      data => { this.testModel = FactModel.fromJson(JSON.parse(data)); }, 
      err => console.log(err) 
    ); 
    } 
} 

này hoạt động nếu một đối tượng xuất phát từ server..but Tôi cố gắng để tạo ra một quan sát mà sẽ làm việc với các cuộc gọi hiện tại() gọi cho một chuỗi tĩnh (điều này xảy ra khi testModelService.fetchModel() không được đưa ra một uuid) để có xử lý liền mạch trong cả hai trường hợp. Điều này có thể không?

Trả lời

70

Có lẽ bạn có thể thử sử dụng phương pháp of của lớp Obserable:

import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/observable/of'; 

public fetchModel(uuid: string = undefined): Observable<string> { 
    if(!uuid) { 
    return Observable.of(new TestModel()).map(o => JSON.stringify(o)); 
    } 
    else { 
    return this.http.get("http://localhost:8080/myapp/api/model/" + uuid) 
      .map(res => res.text()); 
    } 
} 
+0

Điều đó thật tuyệt vời! Nó đã làm việc! Tôi đã thử nhiều thứ như Observable.from() vv .. Tài liệu API cho Quan sát không phải là tài liệu thân thiện nhất/thân thiện nhất vào thời điểm này! Cảm ơn :) –

+2

Có, đã đồng ý ;-) Toán tử 'from' là dành cho mảng ... –

+2

@ThierryTemplier có cách nào để thực hiện loại hành vi này bằng cách sử dụng mâm cặp Angular 2 không? Ví dụ: thiết lập kết nối mô phỏng trong lớp học, với phản hồi giả? – Jefftopia

13

Mọi thứ dường như đã thay đổi kể từ góc 2.0.0

import { Observable } from 'rxjs/Observable'; 
import { Subscriber } from 'rxjs/Subscriber'; 
// ... 
public fetchModel(uuid: string = undefined): Observable<string> { 
    if(!uuid) { 
    return new Observable<TestModel>((subscriber: Subscriber<TestModel>) => subscriber.next(new TestModel())).map(o => JSON.stringify(o)); 
    } 
    else { 
    return this.http.get("http://localhost:8080/myapp/api/model/" + uuid) 
      .map(res => res.text()); 
    } 
} 

Chức năng .next() sẽ được kêu gọi của bạn người đăng kí.

+1

Tôi đã di chuyển sang Angular 2.1.2 .. Cách cũ dường như vẫn được hỗ trợ .. Bạn có thể vui lòng giải thích tại sao đây là giải pháp tốt hơn hay là quy ước? Sau đó tôi sẽ thay đổi nó ở tất cả các vị trí trong mã của tôi và tôi sẽ chấp nhận lại ..Thanks –

+5

@MichailMichailidis, với một tháng nhìn lại, có vẻ như cả hai đều hợp lệ, sự khác biệt chính là giải pháp của Thierry yêu cầu bạn import chức năng 'of' của rxjs, như' import 'rxjs/add/observable/of'' –

+0

Điều này thực sự đã cứu được ngày của tôi. Tuyệt vời nhất – suryakiran

1

Đây là cách bạn có thể tạo một quan sát đơn giản cho dữ liệu tĩnh.

let observable=Observable.create(observer => { 
      setTimeout(() => { 
      let users = [{username:"balwant.padwal",city:"pune"}, 
         {username:"test",city:"mumbai"}] 
      observer.next(users); // This method same as resolve() method from Angular 1 
      console.log("am done"); 
      observer.complete();//to show we are done with our processing 
      // observer.error(new Error("error message")); 
      }, 2000); 

     }) 
    to subscribe to it is very easy 

    observable.subscripe((data)=>{ 
    console.log(data); // users array display 
    }); 

Tôi hy vọng câu trả lời này hữu ích. Chúng tôi có thể sử dụng cuộc gọi HTTP thay vì dữ liệu tĩnh.

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