2017-10-27 3 views
1

웹 서비스에서 JSON 데이터를 가져오고 있습니다. 현재 실시간으로 이러한 데이터를 표시하는 웹 페이지가 있지만 F5 키를 눌러 페이지를 수동으로 새로 고치지 않으면 새로운 값이 표시되지 않습니다. 어떻게 새로운 응답을 듣고 최근 데이터를 실시간으로 Html에 표시합니까? 불명확 한 점이 있으면 알려주십시오. Angular4 - 웹 서비스의 데이터를 실시간으로 어떻게 새로 고 칩니 까?

구성 요소

ngOnInit(): void { 
IntervalObservable.create(1000) 
    .subscribe(() => { 
    this.appService.getDataLN().subscribe(resLN => { 
     // 
     ]; 
     names.forEach(name => { 
     this.findLastValueLN(resLN, name); 
     }) 
    }, error => console.log(error)) 


    this.appService.getDataLS().subscribe(resLS => { 
     let names = [ 
     // 
     ]; 
     names.forEach(name => { 
     this.findLastValueLS(resLS, name); 
     }) 
    }, error => console.log(error) 
    )} 


    findLastValueLN(resLN, name: String) { 
let index = resLN.Object.Table.findIndex(d => 
d.objectName[d.objectName.findIndex(objectName => objectName === name)]); 
if (resLN.Object.Table[index].objectName == "status") { 
    if (resLN.Object.Table[index].LastValue == "on") { 
    let index_A = resLN.Object.Table.findIndex(actual => 

HTML

<div>{{this.arrLN_[0]</div> 
//expected arrLN_[2] to be printed only when status is off.. 
<div>{{this.arrLN_[2]</div> 

답변

0

당신이 뭔가를 찾고있는 당신에게 감사?

ngOnInit(){ 
    IntervalObservable.create(1000) 
     .subscribe(() => { 
      this.appService.getDataLN().subscribe(res => { 
       let names = [//some name fileds that I need to serach from JSON]; 
       names.forEach(name => { 
        this.findLastValueLN(res, name); 
       }) 
      }, error => console.log(error);); 
      this.appService.getDataLK().subscribe(res => { 
       let names = [//some name fileds that I need to serach from JSON]; 
       names.forEach(name => { 
        this.findLastValueLN(res, name); 
       }) 
      }, error => console.log(error);); 
     } 
     }); 
} 

이렇게하면 매초 백엔드를 근본적으로 폴링하고 결과를 업데이트합니다. :)

.takeWhile observable 수정자를보고 해당 구성 요소가 활성화되어있을 때만 코드가 실행되도록 할 수도 있습니다.

당신이 당신의 구성 요소에 변수를 선언 할 수
+0

그래서 구독 초기에 ngOnInit을 초기화합니까? 또는 모든 구독에 대해이 작업을 수행해야합니까? – James

+0

기본적으로 http promise-> subscription 모델을 단일 백엔드 호출로 생각할 수 있습니다. 그것은 아약스 요청을 생성하고, 실행하고, 리턴하고, 데이터를 할당하고, 스스로를 닫습니다. 데이터를 새로 고치려면 기본적으로 구성 요소에 전체 프로세스를 "다시 시작"하도록 알리는 관찰 가능 개체를 만들어야합니다. "관찰 가능한 타이머"에 여러 구독을 넣을 수 있습니다. 기본적으로 모두가 동시에 다시 시작된다는 의미입니다. 또는 예를 들어 여러 타이머를 만들 수 있습니다. 다른 주파수를 할당해야합니다. (즉, 매 초마다 하나씩 다시 시작하지만 매 3 초마다 다른 것을 다시 시작하십시오) – vicbyte

+0

그래서 두 개의 별도 http.get.request를 사용하여 서로 다른 끝점에서 데이터를 추출하고 component.ts에서 두 개의 구독을 가져옵니다. 하지만 난 여전히 내 HTML에 변경 사항을 보지 못했습니다 .. – James

1

:

result = Observable<any>; 

다음 방식으로 서비스 전화 : HTML 파일에서

this.result = myservice.getDataLN(); 

, 당신은 항상 새로운를 표시하는 비동기 파이프를 사용 할 수 있습니다 값을 component.ts에 등록하지 않고 html 파일에 넣으십시오.

{{result | async }} 
관련 문제