NativeScript 和 Observables

NativeScript and Observables

我目前是 Nativescript 和 Angular 的新手。我使用 laravel 创建了一个 API,它工作正常。现在,我正在尝试连接 NativeScript/Angular 中的 API 并从中获取数据。我已按照本教程作为指南 Alex Ziskind

我的 API 是在 Laravel 中使用 PHP 构建的,我的调用在 Postman 中运行良好。我也可以获取 som 数据,但我不能 return 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>

航站楼

因为 this.itemService.getItems() returns 一个 observable 你必须在你的打字稿文件中订阅它或者在你的模板上使用 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>