2017-04-21 12 views
0

를 업데이트하지 내 서비스를 여기각도 4 PouchDB 여기에 서비스

export class LunchService { 

    private db: any; 
    lunches: any = []; 

    constructor(
    private serverService: ServerService, 
    private configService: ConfigService, 
) { 
    this.db = new PouchDB(configService.config.dbServer + '/' + configService.config.dbName); 

    this.db.find({ 
     selector: { 'type': 'lunch' }, 
    }).then((result) => { 
     // HERE 
     this.lunches = result.docs; 
    }).catch(function(err) { 
     console.log(err); 
    }); 
    } 
} 

export class ListingComponent { 

    lunches: any = []; 

    constructor(
    private lunchService: LunchService 
) { 
    // IS EMPTY WHEN SET IN SERVICE? 
    this.lunches = this.lunchService.lunches; 
    } 
} 

왜 점심 식사 서비스의 변수에 대한 변경은 구성 요소에 반영하지 않습니다 내 compnent이다? 컨트롤러의 점심 파라메터가 채워지지 않습니다.

변경 감지에 있지 않습니까? 그러나 어떻게 작동 시키는가?

답변

1

문제를 해결하기 위해 다음과 같이 결론을 냈습니다. 서비스의 데이터가 공유되기 때문에 이것이 만족스러운 해결책으로 보일 수 있지만 최선이라고 확신하지는 못합니다.

나는 돌아 파우치 DB의 상호 작용을위한 새로운 서비스를 추출 관찰 :
export class PouchDbService { 

    private db: any; 

    constructor(
    private configService: ConfigService 
) { 
    this.db = new PouchDB(configService.config.dbServer + '/' + configService.config.dbName); 
    } 

    findDocs(searchParams) { 
    return new Observable(observer => { 
     this.db.find(searchParams).then((response) => { 
     observer.next(response); 
     }).catch((err) => { 
     console.log(err); 
     }); 
    } 
    ); 
    } 
} 

지금 내 점심 식사 서비스에 내가 행동 주체 만들어 내 구성 요소의

export class LunchService { 

    lunches: any = new BehaviorSubject([]); 

    constructor(
    private pouchDb: PouchDbService 
) { 
    this.getLunches().subscribe((response) => { 
     this.lunches.next(response['docs']); 
    }); 
    } 

    getLunches() { 
    return this.pouchDb.findDocs({ 
     selector: { type: { $eq: 'lunch' } } 
    }); 
    } 
} 

마지막을 내가 다시 구독하십시오 :

export class ListingComponent implements OnInit { 

    lunches: any; 

    constructor(
    private lunchService: LunchService 
) { } 

    ngOnInit(): void { 
    this.lunchService.lunches.subscribe((lunches) => { 
     this.lunches = lunches; 
    }); 
    } 

} 

잘 작동하고 구성 요소를 잘 업데이트합니다. 이것이 올바른 기술이라면 나는 조금 확신 할 수 없다. 두 번 구독해야합니까?

보통 (비 파우치 db/일반 http 호출) 비헤이비어 주제가 아닌 서비스 변수를 할당 할 수 있으며 이로 인해 구성 요소/UI의 변경 사항이 반영됩니다. 하지만 파우치가 사용하는 것처럼 나는 관측 가능하게 변환하고 데이터를 그런 방식으로 가져와야했습니다.

의견이 있으십니까?