更新Observable对象的属性(Angular)

时间:2018-02-23 16:14:27

标签: angular observable

我即将问一个可能是假的问题,但我确实遇到了Observables的问题,所以我试试。
我有一个对象,我想成为一个Observable。让我们假设对象是这样的例子:

export class Example {
  public property1: string;
  public property2: string;
}

在一个组件中我有类似这样的东西:

export class Component {
  public myExample: Observable<Example>;

  constructor(){}

  myFunction() {
    this._translateService.service
     .get('SOMETHING')
     .subscribe(response => 
       myExample.property1 = response);
  }
}

_translateService返回一个Observable。

此示例无效。如何实现某些东西来重现这种行为?

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

使用map运算符:

export class Component {
  public myExample: Observable<Example>;

  constructor(){}

  myFunction() {
    this.myExample = this._translateService.service
     .get('SOMETHING')
     .map(response => {
          let example = new Example();
          example.property1 = response;
          return example
      })

}

答案 1 :(得分:0)

Safiyya的解决方案运作良好。另一种使其有效的方法可能是:

public HashMap getPhoneContacts() {

    ArrayList contactList=null;
    ContentResolver cr = getContext().getContentResolver(); //Activity/Application android.content.Context
    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null
            , null, null, null);
    if(cursor.moveToFirst())
    {
        contactList = new ArrayList<String>();
        do
        {
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String contactName=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

            if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
            {
                Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{ id }, null);
                while (pCur.moveToNext())
                {
                    String contactNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    //String contactId = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    String noramliseNum;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                        noramliseNum = PhoneNumberUtils.normalizeNumber(contactNumber);
                    }else{
                        noramliseNum=contactNumber.replaceAll("\\s","");
                    }
                    phoneContacts.put(noramliseNum,contactName);
                    break;
                }
                pCur.close();
            }

        } while (cursor.moveToNext()) ;
    }

    return phoneContacts;
}