2017-01-23 79 views
0

如何thumbnail[0]檢查"no_cover"值,並將其替換到asset/sss.jpg作秀listpage 我嘗試設置在Listpage.html <img src="{{item.LINKS.thumbnail[0]}}">,這個節目只是縮略圖[0]爲http://xxx.jpghttp://xxx.jpg,但我不知道設置 「no_cover」如何JSON對象校驗值ionic2

myjson

" DOCSET":{ 
     "DOC":[ 
     { 
     "LINKS":{ 

      "thumbnail":"http://yyy.jpg", 
      "thumbnail":"http://....jpg"} 
     }], 
     "DOC":[ 
     { 
     "LINKS":{ 

      "thumbnail":"http://xxx.jpg", 
      "thumbnail":"http://....jpg"} 
     }], 
     "DOC":[ 
     { 
     "LINKS":{ 

      "thumbnail":"no_cover",  <<<< 
      "thumbnail":"http://....jpg"} 
     }] 
    } 

編輯 - 你的JSON應該如何看待

因爲我(ivaro18)認爲你手動編寫了你的​​JSON並且沒有複製一個響應對象。讓我來告訴你什麼是有效的JSON的樣子:

{ 
    "DOCSET" : [ 
     { 
      "DOC" : { 
       "LINKS" : [ 
        { 
         "thumbnail" : "http://.....jpg" 
        }, 
        { 
         "thumbnail" : "http://.....jpg" 
        }     
       ] 
      } 
     }, 
     { 
      "DOC" : { 
       "LINKS" : [ 
        { 
         "thumbnail" : "http://.....jpg" 
        }, 
        { 
         "thumbnail" : "http://.....jpg" 
        }     
       ] 
      } 
     }, 
     { 
      "DOC" : { 
       "LINKS" : [ 
        { 
         "thumbnail" : "no_cover" 
        }, 
        { 
         "thumbnail" : "http://.....jpg" 
        }     
       ] 
      } 
     } 
    ] 
} 

END編輯


listpage.html

<ion-list> 
    <ion-item *ngFor="let item of foundRepos"> 
    <ion-thumbnail item-left > 
     <img src="{{item.LINKS.thumbnail[0]}}"> <!--I have no idea to set it --> 
    </ion-thumbnail> 
</ion-list> 

list.page.ts

this.http.get("my_url") 
.subscribe(data =>{ 
    this.foundRepos = data.json().DOCSET.DOC; 
        },error=>{ 
       err => console.error(err), 
       () => console.log('getRepos completed') 
      ); 
+1

你的JSON似乎被打破:你有3個開放方括號'['沒有對應的右括號']' – elf337

+0

@ elf337哦編輯! ,你能幫我嗎?T^T – fongfuse

+0

你的JSON好像有'DOC'這樣的重複鍵,這使得它無效,無法正常工作。 – 2017-01-23 14:34:57

回答

2

所以,首先你發佈的JSON是無效的。什麼它可能是(因爲你打印它像你說的)

我從你的問題理解什麼是下面的,你有<img src="{{item.LINKS.thumbnail[0]}}">但是,這將引發一個404時,返回no_cover,這就是爲什麼編輯你的問題,當item.LINKS.thumbnail[0]等於'no_cover'你要顯示的圖像assets/sss.jpg

那麼,我們如何使用它來顯示'assets/sss.jpg'而不是'no_cover'?這就是所謂的Elvis operator (? :)

讓我們假設一個if語句來下列工程建設:

if(expression) { 
    result = whenExpressionIsTrue 
} else { 
    result = whenExpressionIsFalse 
} 

,我們可以與貓王運營商這樣改寫:

result = someExpression ? whenExpressionIsTrue : whenExpressionIsFalse

因此,讓我們來看看您的問題,我們如何使用if -statement做到這一點?

if(item.LINKS.thumbnail[0] == 'no_cover') { 
    someVariable = 'assets/sss.jpg'; 
} else { 
    someVariable == item.LINKS.thumbnail[0]; 
} 

現在與貓王運營商縮短:

someVariable = item.LINKS.thumbnail[0] == 'no_cover' ? 'assets/sss.jpg' : item.LINKS.thumbnail[0]; 

現在,這可以在HTML中使用像這樣:

<img 
    [src]="item.LINKS.thumbnails[0] == 'no_cover' ? 'assets/sss.jpg' : item.LINKS.thumbnails[0]" 
/> 
+0

這看起來更好,在我看來,你也可以使用if語句,只要你使用數據綁定'[src]'(或'[attr.src]'不再完全確定)就像'[src] =「if(....){' assets/sss.jpg'} else {....}' – Ivaro18