source

Angular의 http 데이터와 유사한 정적 데이터에서 관찰 가능을 생성하는 방법은 무엇입니까?

itover 2023. 2. 11. 09:13
반응형

Angular의 http 데이터와 유사한 정적 데이터에서 관찰 가능을 생성하는 방법은 무엇입니까?

다음 방법으로 서비스를 이용하고 있습니다.

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

컴포넌트 컨스트럭터에서 다음과 같이 서브스크라이브합니다.

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

이것은 오브젝트가 서버로부터 온 경우 동작하지만, 지정된 환경에서 동작하는 관찰 가능을 작성하려고 합니다.subscribe()스태틱 스트링을 호출합니다(이것은,testModelService.fetchModel()는 UUID를 수신하지 않기 때문에, 어느 경우라도 심리스한 처리가 가능합니다.

아마도 당신은 그 방법을 사용해 볼 수 있을 것이다.Observable클래스:

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

2018년 7월 현재,RxJS 6값에서 Observable을 얻는 새로운 방법은 다음과 같습니다.of연산자는 다음과 같습니다.

import { of } from 'rxjs';

그런 다음 다음과 같이 값에서 관측 가능한 값을 생성합니다.

of(someValue);

참고: 예전에는 이 모든 것들을Observable.of(someValue)현재 받아들여지고 있는 답변에서처럼요.다른 RxJ6의 변경에 대한 좋은 기사가 여기에 있습니다.

Angular 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());
  }
}

.next()함수가 가입자에게 호출됩니다.

이렇게 하면 정적 데이터에 대한 단순 관측 가능을 생성할 수 있습니다.

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.subscribe((data)=>{
  console.log(data); // users array display
});

이 답변이 도움이 되길 바랍니다.스태틱 데이터 대신 HTTP 콜을 사용할 수 있습니다.

2021년 5월 현재 값에서 관측 가능 값을 얻는 새로운 방법은 다음과 같습니다.

Import:

import "rxjs/add/observable/of"
import { Observable } from "rxjs/Observable"

다음과 같이 사용합니다.

Observable.of(your_value)

이렇게 하면 데이터에서 Observable을 생성할 수 있습니다. 이 경우 쇼핑 카트를 유지 관리해야 합니다.

service.ts를 클릭합니다.

export class OrderService {
    cartItems: BehaviorSubject<Array<any>> = new BehaviorSubject([]);
    cartItems$ = this.cartItems.asObservable();

    // I need to maintain cart, so add items in cart

    addCartData(data) {
        const currentValue = this.cartItems.value; // get current items in cart
        const updatedValue = [...currentValue, data]; // push new item in cart

        if(updatedValue.length) {
          this.cartItems.next(updatedValue); // notify to all subscribers
        }
      }
}

컴포넌트.ts

export class CartViewComponent implements OnInit {
    cartProductList: any = [];
    constructor(
        private order: OrderService
    ) { }

    ngOnInit() {
        this.order.cartItems$.subscribe(items => {
            this.cartProductList = items;
        });
    }
}

언급URL : https://stackoverflow.com/questions/35219713/how-to-create-an-observable-from-static-data-similar-to-http-one-in-angular

반응형