簡體   English   中英

角度2:使用服務在組件之間共享數據

[英]Angular 2: Using service to share data between components

我正在嘗試使用服務來定義幾個視圖之間的共享資源client 我首先從索引中選擇client並進行設置:

itemTapped(event, client) {
  this.clientService.get(`/${client.id}?model=client`, this.current_user.auth_token)
    .subscribe(
      data => {
        this.clientService.setClient(data)
        this.navCtrl.push(ClientGenericPage, {
          client_id: data['id'],
          tab: 'profile',
          current_user: this.current_user
        });
      },
      err => { 
        this.clientService.handleResponse("Ut oh.. Could not locate the client !"),
        this.clientService.hideLoader()
      },
      () => this.clientService.hideLoader()
    )
}

export class ClientService {

  private client = new Subject<any>();


  constructor (private http: Http, private toastCtrl: ToastController, public storage: Storage ) {

  }

  setClient(client) {
    this.client.next(client)
  }

  getClient() {
    return this.client.asObservable();
  }

  get(url, token):Observable<Response> {
    let headers = new Headers();
    headers.append("authentication", token );
    let options = new RequestOptions({ headers: headers });

    let final_url = `${this.baseUrl}${url}`

    return this.http.get(final_url, options)
      .map(this.extractData)
      .catch(this.handleError)
  }
}

然后,我嘗試獲取剛剛設置的客戶端並訂閱該客戶端,以便可以在此視圖及其同級中檢測到對client更改:

this.clientService.getClient()
  .subscribe(
    val => {
      console.log(val)
      this.client = val
    },
    err => console.log(err),
    () => {}
)

但是對getClient()調用永遠不會返回錯誤或任何錯誤。 我的可觀察物在做什么?

編輯:這是組件:

@Component({
  selector: 'page-client-details',
  templateUrl: 'client-details.html',
  providers: [FilterObject, ClientService]
})
export class ClientDetailsPage {
  client:any;
  constructor(
    public navCtrl: NavController, 
    public navParams: NavParams, 
    private filterObject: FilterObject, 
    public http: Http,
    public modalController: ModalController,
    private clientService: ClientService,
    private app: App
  ) {

  this.clientService.getClient()
    .subscribe(
      val => {
        console.log(val)
        this.client = val
      },
      err => console.log(err),
      () => console.log("completed")
    )
}

為什么要在組件類中定義ClientService。 與ClientService相關的單個組件嗎?

您需要在app.module.ts中提供ClientService,並在組件類中注入clientservice。 如果您在組件中提供clientservice,它將為該組件創建不同的實例

app.module.ts

 providers: [ ClientService  ],

ClientDetailsPage.ts刪除提供程序:[ClientService]

{
constructor(clientService  : ClientService  ) { 

  }
}

您可以嘗試使用BehaviorSubject代替Subject,它需要提供的唯一更改是默認值。 我修復了同樣的錯誤,但沒有發現問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM