Я изучаю дартс и пытаюсь создать простое веб-приложение, которое должно позволить создать пользователя.
Но когда я пытаюсь его запустить, появляется следующее сообщение:
[SEVERE] build_web_compilers|entrypoint on web/main.dart (cached): Unable to find modules for some sources, this is usually the result of either a bad import, a missing dependency in a package (or possibly a dev_dependency needs to move to a real dependency), or a build failure (if importing a generated file).
Please check the following imports:
import 'package:Muellbot/app_component.template.dart' as ng;
from Muellbot|web/main.template.dart at 9:1import 'package:Muellbot/app_component.template.dart' as ng;
from Muellbot|web/main.dart at 2:1[SEVERE] Failed after 2.2s
Вот мои файлы:
main.dart
import 'package:angular/angular.dart';
import 'package:Muellbot/app_component.template.dart' as ng;
import 'package:angular_router/angular_router.dart';
import 'main.template.dart' as self;
@GenerateInjector(
routerProvidersHash,
)
final InjectorFactory injector = self.injector;
void main() {
runApp(ng.AppComponentNgFactory, createInjector: injector);
}
appComponent.dart
import 'package:angular/angular.dart';
import 'package:angular_router/angular_router.dart';
import 'src/routes.dart';
@Component(
selector: 'my-app',
styleUrls: ['app_component.css'],
templateUrl: 'app_component.html',
directives: [routerDirectives],
exports: [RoutePaths, Routes],
)
class AppComponent {
}
appComponent.html
<h1>Müllbot</h1>
<nav>
<a [routerLink] = "RoutePaths.home.toUrl()"
[ routerLinkActive] = "'active'">Home</a>
<a [routerLink] = "RoutePaths.newUser.toUrl()"
[routerLinkActive] = "'active'">Neuen Benutzer anlegen</a>
</nav>
<router-outlet [routes] = "Routes.all"></router-outlet>
<img src = "logo.png" width = "50%">
routes.dart
import 'package:angular_router/angular_router.dart';
import 'route_paths.dart';
import 'home_component.template.dart' as home_template;
import 'create_new_user_component.template.dart' as new_user_template;
export 'route_paths.dart';
class Routes {
static final home = RouteDefinition(
routePath: RoutePaths.home,
component: home_template.HomeComponentNgFactory,
);
static final newUser = RouteDefinition(
routePath: RoutePaths.newUser,
component: new_user_template.NewUserComponentNgFactory,
);
static final all = <RouteDefinition>[
home,
newUser,
];
}
routhe_paths.dart
import 'package:angular_router/angular_router.dart';
class RoutePaths {
static final home = RoutePath(path: 'home');
static final newUser = RoutePath(path: 'newUser');
}
home_component.html
<h4>Hallo {{user.firstName}}</h4>
home_component.dart
import 'package:angular/angular.dart';
import 'user.dart';
@Component(
selector: 'home',
templateUrl: 'home_component.html'
)
class HomeComponent {
User user = new User('Axel', 'Foley', '[email protected]');
}
create_new_user_component.html
<h3>Neuen Benutzer anlegen</h3>
<div>
<span *ngIf = "!create" id = "error">Fehler</span>
<span *ngIf = "create" id = "success">Benutzer angelegt</span>
<table>
<tr>
<td><label>Vorname:</label></td><td><input #firstName/></td>
<td><label>Nachname:</label></td><td><input #lastName/></td>
</tr><tr>
<td><label>Email:</label></td><td><input #email/></td>
</tr><tr>
<td><label>Passwort:</label></td><td><input #password/></td>
<td><label>Passwort wiederholen:</label></td><td><input #passwordRe/></td>
</tr><tr>
<td><button (click) = "add(firstName.value, lastName.value, email.value, password.value)">Hinzufügen</button></td>
</tr>
</table>
</div>
create_new_user_component.dart
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart';
import 'package:angular/angular.dart';
@Component(
selector: 'new-user',
templateUrl: 'create_new_user_component.html'
)
class NewUserComponent {
bool create = false;
final Client _http;
static final _headers = {'Content-Type': 'application/json'};
final url = "http://localhost:4040/user/new";
Future<void> add(String firstName, String lastName, String email, String password) async {
try {
final response = await _http.post(url, headers: _headers, body: json.encode({'firstName': firstName, 'lastName': lastName, 'email': email, 'password': password}));
if (response.statusCode == 200) {
create = true;
}
} catch (e) {
throw new Exception(e);
}
}
}
Спасибо, но это ошибка, файлы называются "app_component. *"
Если вы заглянете в свой каталог .dart_tool/build/generated/Muellbot/lib/
, вы увидите файл app_component.template.dart
?
Нет, такого файла нет.
Хорошо - значит, по какой-то причине он не генерируется. Есть ли у вас другие ошибки в сборке? Вы также можете перейти к / $ graph (в режиме обслуживания), ввести в поле поиска «lib / app_component.template.dart» и нажать «Поиск». Находит ли узел? Если да, можете ли вы скопировать / вставить информацию для него в правом верхнем углу?
Это результат: Ошибка при запросе запроса «ib / app_component.template.dart». 404 Not Found Не удалось найти ресурс для пути «ib / app_component.template.dart». Пробовал: - Muellbot | ib / app_component.template.dart - Muellbot | web / ib / app_component.template.dart
Похоже, вы пропустили ведущий l
, должен быть lib/app_component.template.dart
О, ты прав, мне очень жаль. Итак, вот правильный вывод: ID: Muellbot | lib / app_component.template.dart Сгенерировано: true Скрыто: true Состояние: NodeState.mayNeedUpdate Было Вывод: false Ошибка: true Фаза: 907 Globs: null
Позвольте нам продолжить обсуждение в чате.
Хорошо, удаление
<span *ngIf = "!create" id = "error">Fehler</span>
<span *ngIf = "create" id = "success">Benutzer angelegt</span>
помогло.
Но теперь у меня другая ошибка. Сервер загружается, и когда я захожу на страницу, он просто говорит
Loading...
В консоли я получаю сообщение
TypeError: e.message is undefined
Эту проблему можно решить, полностью импортировав пакеты, включая ваш Project dir path
, в ваш routes.dart
.
убедитесь, что импорт выглядит так
import 'package:Muellbot/home_component.template.dart' as home_template;
import 'package:Muellbot/create_new_user_component.template.dart' as new_user_template;
а не это
import 'home_component.template.dart' as home_template;
import 'create_new_user_component.template.dart' as new_user_template;
По крайней мере, в приведенном выше примере вы написали
templateUrl: 'app_component.html'
, но назвали свой HTML-файлappComponent.html
. Это может быть источником вашей проблемы?