NativeScript和可观察项

问题描述 投票:0回答:1

我目前是一个Nativescript和Angular的菜鸟。我已经用laravel创建了一个API,并且运行良好。现在我试图在NativeScriptAngular中连接并从我的API中获取数据。我按照下面的教程进行了操作。Alex Ziskind.

我的API是用PHP在Laravel中建立的,我的调用在Postman中工作正常。我也能够获得一些数据,但我不能在HTML中返回它。

我的服务

export public ItemService {
    getItems():Observable<Item[]> {

        const authToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIyIiwianRpIjoiZmIzYjJmYzg3MWY2YTc5ZjVjMTM3NDNmMDllNGUwNzYwZDkyODljMmVjNTE3NGZiNDMzZTRjMGQ0MjBjYTJmYjlhMGQ1ZmFjNTQ1NmQ3ODkiLCJpYXQiOjE1OTA2NTAyMjksIm5iZiI6MTU5MDY1MDIyOSwiZXhwIjoxNjIyMTg2MjI5LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.Y3kidP6TP__DrwBDcGuk6M4p76INEdxG8UWrdakfkfcjCOlmHA0pb7a8vTvRQl2WLA_gwNWD4qA64ToOZb1YxkWCe8ESBTRDBg9Xq3DbSsZzlBZb9v8zS8PEeJVnfMtmxVIJb8IEU82DYGbpky-XdDfn67ge6fM3jTvwyivthlhaQLkjsh8e3VKlUx0P8lSxoHVw-N0369otRU6X0CTghl5lg9Khru4AtdJIBL3AOQAFEZmpzAGg9xZkvY923VkgkBHXt-adfvBwG2ZP0UhUVht-aiKK2z9HlR0eQ_-eqYlo-fqmTAE0U1k5ET99jbap8xO0dXJfdYVF0cAJ7p6FNjMoougwR89kz2xCcUHyFnPli3HcZx7j8IKDhqvneL8oWjaJuO41z1O69qsbk7_g8iLVI5vQlv6slrIe2YSbABkHzzCGndFX-smZkugB8aNmoRGpX8RJ5y5HxE6pJG8nn8CYih5ednDlWaTUBGk0p4zpck2z8788zyX41sPdB1oqR2gO0_CL-pBjCdTgDYXi_hy49_SO_4Vsf8lPL7vyhhvv7w_KgV7Jc7ju3Xm4HRLUG56K8CMy1KEfVuTDYs0gnybuFolfv2haeVgc_2h2A65O5nuUZg_RpePrSBZEftLsITWa3lUvnF380_htio-Zp3gXs3INoH7ms5KdTPt3mZ8";
        const URL = "http://10.0.2.2:8000/api/source";

        /*return this.http.get<Item[]>(
            URL,
            { headers: new HttpHeaders().append("Authorization", `Bearer ${authToken}`) }
        )*/

        const res = this.http.get<Item[]>(
            URL,
            { headers: new HttpHeaders().append("Authorization", `Bearer ${authToken}`) }
            )

            console.log()

        return res;

    }

    getItem(id) { }
    /*
        getItem(id: number): Item {
            return this.items.filter((item) => item.id === id)[0];
        }
    */
}

我的组件

export class ItemsComponent implements OnInit {
    public items$: Observable<Item[]>;

    constructor(private itemService: ItemService) { }

    ngOnInit(): void {
     this.itemService.getItems();
     console.log(this.itemService.getItems())
    }
}

我的模板

<StackLayout class="page">
<ListView height="300" [items]="items$ | async" class="list-group">
    <ng-template let-item="item">
        <label [text]="item.data.first_name" class="list-group-item"></label>
    </ng-template>
</ListView>
</StackLayout>

终端Terminal log

nativescript nativescript-angular
1个回答
2
投票

this.itemService.getItems() 返回一个观测值,你将不得不在你的typScript文件中订阅它,或者使用 async 管道上的模板。

使用 subscribe:

items;

constructor() {
  this.itemService.getItems().subscribe(res => {
    this.items = res;
  })
}

// in your template (Label here is just an example)

<Label [text]="items"></Label>

使用 async:

items$ = this.itemService.getItems();

// in your template (Label here is just an example of how you would use the async pipe)

<Label [text]="items$ | async"></Label>
© www.soinside.com 2019 - 2024. All rights reserved.