Цикл Angularjs через результат API, присвоенный $ scope, вернется как «неопределенный» - PullRequest
0 голосов
/ 06 мая 2019

Здравствуйте, я хотел бы знать, как я могу выполнить цикл по API-результату, назначенному $ scope. Результат показывает неопределенное

мой HTML-код:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Api_combine</title>
    <script src="./js/angular.js"></script>
</head>
<body ng-app="myApp" ng-controller="mainCtrl">
    {{ someFunction() }}
    <script src="./scripts/app.js"></script>
    <script src="./scripts/apiS.js"></script>
</body>
</html>

код моего app.js:

let app = angular.module('myApp', []);
app.controller('mainCtrl', function($scope, apiS) {

    apiS.getTodos().then(res => $scope.todos = res);

    $scope.someFunction = () => {
        for (let x = 0; x < $scope.todos.length; x++) {
            const todo = $scope.todos[x];
            if (todo.userId == 1 && todo.id == 2) {
                return "found!!!"
            }
        }
    }
});

мой сервисный код API:

app.service('apiS', function($http) {
    this.getTodos = function() {
        return  $http.get('https://jsonplaceholder.typicode.com/todos');
    }
});

Я бы хотел пройтись по $ scope.todos и получить желаемый результат в DOM.

Но в консоли появится надпись undefine

Как я могу сделать это правильно?

1 Ответ

0 голосов
/ 07 мая 2019

Я добавил .data после разрешения.

apiS.getTodos().then(res => $scope.todos = res.data);
...